Threading in Actionscript

One obstacle sometimes encountered while using Actionscript is when you have a script that needs to run for a long time. You may have noticed that your application appears to 'freeze' while the long script is running. This is because Actionscript is single threaded. This 'freeze' happens because your script is blocking all other scripts from running, including the script that updates the UI. In languages that support threading, you would simply put your long script in a thread and the environment would handle running the script while not blocking other running scripts. In Actionscript we can solve this problem by something called 'pseudo-threading'. We can breaking up our script in to smaller pieces and pause between execution of each piece, therefor allowing other necessary scripts to run in-between.

Here is a blog that describes how to do this. You can create a PseudoThread object and pass it a threadFunction and a threadObject. The threadFunction should execute a small piece of the work and the threadObject should store the state. The PseudoThread class will call the threadFunction as many times as it thinks it can get away with per frame. This works fine, but it only gives you one extra thread.

I have expanded on the idea and created three classes: PseudoThread, PseudoThreadPriority and PseudoThreadManager. The PseudoThread holds the threadFunction, priority and threadObject for a thread; the PseudoThreadPriority class determines which thread priority to run next and which thread to execute within that priority; and the PseudoThreadManager is responsible for starting and stopping execution of PseudoThreads.

View the source code and example here (MIT License).

Note: Thread priority will not switch mid-frame and thread starvation prevention is used. This means that you could run a lower thread priority for an entire frame, which might not be ideal for time critical applications like video games.