AS3 execute code atomicly

Tag: actionscript-3 Author: longfei256 Date: 2011-11-11

I have two objects that are searching for one-another on the stage. They move in a certain direction with a certain speed. This is done via the Event.ENTER_FRAME. Once an objects finds the other it will start to do certain modifications on both objects, including stopping it.

Now, a certain problem came into mind. What if Object A finds Object B, start to do some modifications on Object B and the CPU is taken from ObjectA and given to ObjectB. Now, Object B will find ObjectA and will start to do modifications on ObjectA even though ObjectA is already in the process of doing this. This can be fixed with a very simple technique: once ObjectA find ObjectB it calls a lock() method. And objectB won't check for the other object while locked. The problem is that I don't know how to make the checking of the distance between the objects (this is how they find eachother) and the locking in an atomic way.

P.S. I have done a lot of multy-threading programming in Java in the past months so maybe these things don't apply here.


Best Answer

There should be no problem. Flash doesn't do multi-threading.

You can be sure that once an event function is called, it will run without interruption by other events. The only problem that you may need to consider is that you don't know the order in which multiple enter frame events will be executed. If the order matters, you should use a single event which calls your objects' event methods in the desired order.


It does not matter which one is called first. I just wanted to make sure that once one is called it finishes to do it's job before the next one is called.
I just remembered that there is also a priority parameter in addEventListener. Would be useful if the order would matter but doesn't need to be dynamic.