web workers vs. the crazy flies

Here’s a low tech demo of the power of web workers. A hundred flies will swarm randomly. Ones that get too high get sleepy, ones that sink too low get re-caffeinated and ones that cover the least distance will perish.

Click for demo (IE not supported)

Sourcecode is gisted on GitHub

I should start by saying this was not trivial to write. As we will see the web workers API is disarmingly simple but the tripwires are many. The biggest issue is the lack of useful debug support because the global worker object exists in a vacuum.

The basics

Your browser can be serviced by one or more web workers. A worker will perform non-DOM related tasks in a separate thread. This means worker processes are performed asynchronously with respect to the browser (in fact the worker has no access to the browser’s window object, the equivalent global object being self which references the worker). The implications are exciting. Lengthy computational tasks can be undertaken with no effect on browser responsiveness.

A web worker is a .js file which you set as an attribute of a worker object.

var worker = new Worker("buzzWorker.js");

The browser and the worker speak the same language. Messages are sent and received using postMessage and onMessage respectively

//on the browser
worker.onmessage = function(e){
    updateThing(e.data);
}

 var invokeWorker = function(action) {
    worker.postMessage({
        'action': action,
        'things': things
    });
}
//on the worker
{
    //....
    updates.maxDy = 2;
    updates.symbol = '*';
    postMessage(updates);
}

var onmessage = function(e){
    things = e.data.things;
    actions[e.data.action]();
}

By these means data and instructions can be passed to and fro between browser and worker.

Data streaming is by value not by reference. The data is serialized in transit and rebuilt as a new but (hopefully) identical object on the other side. In theory any serialize-able non-DOM object can be streamed. Mozilla, Chrome 5 and Safari 5 support posting of complex objects to workers (thanks to Rick Waldron and Charles Lehner for pointing out bugs in my code which webkit browsers objected to)

IE8 has no web worker support.

The app

The crazy flies app makes use of a web worker to analyze and acting upon the latest data pattern (i.e. which flies are where) while the browser focuses on buzzing them around the screen as fast as possible. Each fly is an instance of a Thing object which recursively moves itself around the screen in a random fashion. Every second the browser posts four instructions to the worker:

intervals[0] = window.setInterval(invokeWorker.curry('updatePaths'),1000);
intervals[1] = window.setInterval(invokeWorker.curry('makeHighestSleepy'),1000),
intervals[2] = window.setInterval(invokeWorker.curry('makeLowestBuzzy'),1000);
intervals[3] = window.setInterval(invokeWorker.curry('killSlowest'),1000);

The first instruction updates the approximate total distance traveled by each living Thing. The other three perform further analysis on the state of Things and then send back the appropriate data to the browser so that it can modify the flies.

The web worker does make a difference. Every second it uses Pythagoras’ theorem to increment the net path-length of each fly and every second it is sorting arrays three ways to find the highest lowest and least traveled flies. When I prototyped the app I first had all processes running in the browser. It limped along with a lengthy freeze every second. In contrast, with a web worker employed the scene plays out seamlessly on my computer (though the fluency may vary based on your processing speed).

Conclusion

JavaScript web workers are in their infancy and the use cases are limited (top of my wish-list is worker partitioning of the browser itself so that DOM events could run in separate threads). Browser support varies from patchy to non-existent and debugging is tough. It’s too early to claim web workers as an industrial strength solution but the outlook is promising, and in the meantime they’re fun to mess around with.

About these ads

24 thoughts on “web workers vs. the crazy flies

  1. nice investigation :)
    the spec didnt said that we can pass other stuff than strings, which sounds stupid, but I guess it was to make things easier for the implementors, but I guess that passing full JSON strings would work … at the price of CPU hog :(
    FF did go further by allowing passing arrays. That sounds good but are you sure other browsers have plans for this ?

    I would have like to play this demo without the Web Workers, to see the lag in action

    and you found a smart way to pass in methods to execute :)

    var onmessage = function(e){
    things = e.data.things;
    actions[e.data.action]();
    }

    well done

    • Thanks for the nice comments!

      >>FF did go further by allowing passing arrays. That sounds good but are you sure other browsers have plans for this ?

      According to the spec:

      interface Worker : AbstractWorker {
        void terminate();
      
        void postMessage(in any message, in optional MessagePortArray ports);
                 attribute Function onmessage;
      };
      • ok, my bad
        they changed the spec to follow the one of Mozilla, I’m pretty sure :)

        no plan for having the same demo working without workers, to see the browser lag difference ?

      • I will try. Also want to try to get this to work with webkit and I need to start planning next blog. And I’ve got my day job too ;-)

        (actually I think you may be right – I did read somewhere that they updated the spec after Mozilla went one better)

  2. Angus, I got the demo to work in Chrome without modifying anything. It just worked (6.0.398.0 (46652) Ubuntu).

    Nice example!

    I wasn’t aware that you could pass in non-serialized objects either.

    • Hey Nick, thats good to know :-) (you saw asterisks and zeds and the gorey death scenes too?)

      I’m on 6.0.437.3 and it does nothing. You’re using a mac right? Maybe works on mac + safari 5 too. I know its only a matter of time until the webkit browsers come up to speed on the spec. (btw just tested on Opera 10.53, belatedly – no dice)

      • No gory death scenes or asterisks, actually. Just the “%” flies buzzing around. Too bad. I am actually on Ubuntu Lucid Lynx.

        Maybe its just me, but Opera seems completely irrelevant now-days. (Was it ever relevant?) I get about 1% of visitors to my sites using Opera…

      • Ok so its NOT working on chrome. The buzzing %s are just the browser. The web worker updates them based on its analysis.

        re. Opera. Yes and No – the only reason they still interest me is they make a hell of an effort to support web specs (although sometimes very badly). I was told they fully implement every HTML 5 tag including all the new input tags

      • Karmic 64 bits and Chrome (6.0.466.0 dev) here. The %, *, and z all show up, with red % (just before death). No crashes, works great, runs to the end.

        Nice work.

  3. I’m reading this from my mobile device, so can’t test for myself, but complex messages are supported in chrome 5, safari 5 and opera 10.6 beta – I have published research illustrating this.

    • Rick – yep you’re right. I’ll update my text accordingly. The next question in how complex. In chrome I’m getting a

      NOT_SUPPORTED_ERR: DOM Exception 9

      Which suggests it doesn’t like the fact each Array member has a property which points to a DOM element. If I have enough time I will try putting the elements in a hash which I can reference with a string

      Thanks for the catch!

      • I’ve had a chance to play around with this and I can see now why you’ve reported that it doesn’t work in anything but FireFox – you’re attempting to pass non-thread safe content (a DOM Element and a function) when the spec clearly dictates that this is not allowed and will not be allowed (so there is no “catching up” that the other browsers have to do). Why it works in FF is because FF strips out the non thread safe contents of your objects in the “things” array when it serializes the message arguments – the webkit implementation does not do this. When this happens, FF processes silently, but incorrectly. It SHOULD throw an error. Basically, message sent through postMessage() are given the JSON scrub (http://www.json.org/) so anything that can be evaluated and restructured as valid JSON will be allowed. postMessage() must conform to the HTML5 Communication specification, notably this:

        http://www.w3.org/TR/2009/WD-html5-20090423/comms.html#posting-messages

        Follow that to the “Safe passing of structured data” spec:

        http://www.w3.org/TR/html5/infrastructure.html#structured-clone

        As for “How complex”:

        http://weblog.bocoup.com/javascript-web-workers-chrome-5-now-supports-complex-messages

      • Thanks, yeah I’m already onto the DOM element issue. BTW I don’t pass a function – just a string reference to a hash of functions on the worker

        Edit: Now removed all DOM objects refs from message. No errors in chrome or safari but not working either. Perhaps its now a race condition that can be solved by putting callbacks on the web worker functions.

  4. “BTW I don’t pass a function – just a string reference to a hash of functions on the worker”

    When I inspect each object in the array on the console it has “start” which is being identified as a function. That’s where I got that from.

  5. I forked it and got it working in Safari.
    http://gist.github.com/449426

    The problem wasn’t actually passing complex messages, but two other things:
    The onmessage function in the worker had to be in the global scope, otherwise it was never called. So I just took off the var keyword.
    The sort functions should use subtraction to compare numbers, not > or b, or a – b instead of a < b.

    • Charles, many thanks. Works in Chrome too now. It was my dumb var in front of onmessage that was the issue (force of habit!). I’ve updated the demo and the post. Great catch!

  6. When passing messages to and from workers, I typically include a ‘type’ property in the anonymous objects carrying the payload, like this:

    x.postMessage({‘type’: ‘debug’, ‘data’: { ‘error’: …, … }})

    or

    x.postMessage({‘type’: someclass.MSG_MSGTYPE, ‘data’: { ‘greeting’: ‘hello’}})

    …or something. That way, I can key off the type value to route messages to appropriate callbacks. This is particularly handy for debugging. You can catch errors in the worker and post a message back to the worker’s parent where you can do what you want with the error information in the payload.

  7. Pingback: RPW 22/06/10: démos HTML5 Web Socket et Web Workers, font répandues, HTML5 microdata, dégradé CSS3 et IE | BrainCracking - Veille technologique sur les applications Web

  8. Pingback: Master List of HTML(5)/JSS/CSS Resources | Emerging Tech Talk

  9. Pingback: List of HTML5 Resources « prasadsambari

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s