“Multithreading” in Actionscript

Multithreading in FlashPlayer? No such thing…

Anyway, if you reached this article, you probalbly know a few things about Flash. Or you know  less than you think you know. Or the other way around. I’m lost…

On short, some processes you write take too much time to complete in just one frame’s time. Your animation locks, interface becomes unresponsive, not so nice. One solution, apart from not doing the task at all :D , is to slice the long task into small pieces of work and have them handled by a so called threads controller until the job is done. If the controller is smart enough, you can even concurrently run several tasks and not lock the player.

But 1000 words  are less then 2 lines of code, so, let’s dive in:

// the ThreadsController it will add some events to stage,
// so let's give it the stage reference
var tc:ThreadsController = new ThreadsController(stage);
 
//your SomeTask has to implement IThread
var task:IThread = new SomeTask;
 
// in this example i choose to end the task
// if it was not finished at the time we want
// to start another
if (tc.isRunning(task))
{
	tc.kill(task);
}
tc.run(task);
 
tc.addEventListener(ThreadEvent.THREAD_READY,
	function(e:ThreadEvent):void {
	if (e.thread != task) return;
	// do something after the task is done
});
 
tc.addEventListener(ThreadEvent.PROGRESS, function(e:ThreadEvent):void
{
	if (e.thread != task) return;
	// update the status of your task in progress,
	// like update a progress bar indication
});

Download: threads.rar

Next: Part II, JPEG Encoder Example


You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

AddThis Social Bookmark Button

14 Responses to ““Multithreading” in Actionscript”

  1. Unfortunately, this doesn’t solve the threading problem. This only provides a wrapper for dispatching an event when a supposed thread has completed. The tricky part would be in the implementation of SomeTask (IThread). That is where this problem gets ugly: how you take a particular time-intensive task and break it up into smaller tasks that can be run in chunks? And maybe there’s no magic class that can be created to solve this problem, but that is the big problem when it comes to trying to recreate background threads in AS.

  2. Wow, senocular…
    10x for dropping by!
    True, true, the tricks are in SomeTask. But a good interface makes the job half done (I’m optimistic :D )
    And if we want more, we can use Java. Then the application is dead before birth because few people can play it. Here is where Flash rulez. Still :D

    Back to IThread, having a thread class makes it easy to cache the loop(s) locals from one slice to the next, because you don’t clutter the class with time slicing code. That code is dealt by the ThreadsController. Once you get used to think in this system, it gets easy.

  3. Depending on the processing size of the thread, you may gain no speed from this because of the event system. Dispatching events is actually a rather time consuming processes. You are much better off just passing in a function reference to the class to act as a callback listener. As a shameless plug, FlashMVC.com framework uses a mock event system that removes some of the bottleneck. This week I will be releasing an update so that the FlashMVC framework will automatically queue up actions scheduled to run if the system starts becoming unresponsive from the load. However, if you want true multithreading (or closer to the real thing), using Pixel Bender will create an addition thread to play with.

  4. With all respect, I think you’re missing the point!
    But first, thanks for dropping by! My small log was never such a point of interest.
    Back to my threads: I had this simple problem in a few of my works. Some tasks take about say, 1-5s to complete. They are simple or imbricated loops. I want the user to be able to continue using the interface, seeing the animations and the progress bar moving. There is no problem in having the “threaded” process taking 3s instead of 2, as long as it doesn’t lock the interface. The result will come later. Certain tasks benefit from this approach while others may not. But usually, it’s better to have a little longer execution time than locking, when the player locks, users will start to question the computer sanity, etc. So this has no much connection with a MVC system, or a global tasks scheduler. Such a thing should be on a level above my little manager.

    And about dispatching versus function reference. I disagree again. When you have one listener, it’s quicker to execute a function, but when you have a list of listeners, it’s the player’s job to handle the list quicker than it can be handled by scripting. ThreadEvents don’t bubble, that makes dispatching quicker than events on display.

    10x again for the time and for the links

    And stay put. Some very interesting stuff is cooking!

  5. Hmm, I still doubt that a non-bubbling event is more efficient that a direct callback function. A single dispatch event requires 1) a new Event object to be created and 2) that Event Object is cloned/reinstanced to ensure the dispatcher can interfere with the event object once a listener has received it. That’s two class instances that needs to be created on top of any other checks that event system has to run.

    However, I still digress from your real point here so please ignore my banterings on micro performance. I struggle with Flash’s performance daily with my work so I tend to be a little OCD on the matter. heh

  6. Typo: dispatcher -can’t- interfere

  7. I did a test:
    1. dispatch to functions stored in a dictionary
    2. dispatch using event dispatcher

    for 100,000 listeners:
    1. ~ .8s
    2. ~ 1.6s

    Yes, dispatching is time consuming. But makes the code more maintainable. Or does it? :D

  8. There recently was a post I read (4got link) where pixelbender was used for ‘multithreading’.

    I’m sure a google search will pop it up.

  9. [...] “Multithreading” in Actionscript [...]

  10. Concerning events, Victor is right. For the purpose of threading like this, event performance is a non-issue. With these threading classes, the number of events per frame for each thread is 1; 2 when the thread is complete. This with the single additional event handler controlling active threads means absolutely no noticeable impact on performance. And if you’re threading anything at all, your performance problems already exist somewhere else.

  11. [...] 10 Responses to ““Multithreading” in Actionscript ”. senocular Says: June 18th, 2009 at 5:38 pm. See the rest here: ActionScript 3 Log » Blog Archive » “Multithreading” in Actionscript [...]

  12. Guys,

    be sure to take a look at wonderful ActionScript Thread Library 1.0 that implements pseudo-threading in AS3: http://www.libspark.org/wiki/Thread/en

    I’m just using it in our latest project and it is really useful for time-consuming tasks though some task-splitting coding needs to be involved.

    Tomas

  13. Ionut Tabirca Says:

    This will help when doing compression on some large files.
    10x
    Tot inainte!

  14. Thank you for the conversation, all.

Leave a Reply

Powered by WP Hashcash