Tuesday, July 14, 2009

Threads for JavaScript!

I recently upgraded to Firefox 3.5, and was browsing the release notes.

In the release notes, there was a quiet reference to the new WebWorkers feature:
Support for native JSON, and web worker threads.
Somehow, I just skimmed over this, but then a separate posting to hacks.mozilla.org woke me up and made me pay more atttention:

Web Workers, which were recommended by the WHATWG, were introduced in Firefox 3.5 to add concurrency to JavaScript applications without also introducing the problems associated with multithreaded programs. Starting a worker is easy - just use the new Worker interface.
Reading a bit of background material, it seems as though the Web Workers feature was partially added to previous releases of Firefox, but wasn't quite ready for prime time. Now it seems that the bespin guys have been actively using this, and have proven it out, and so it's become a Real Feature of Firefox 3.5.

The master documentation at the WHATWG is quite thorough, and contains a lot of examples, including:

  • The simplest use of workers is for performing a computationally expensive task without interrupting the user interface.In this example, the main document spawns a worker to (naïvely) compute prime numbers, and progressively displays the most recently found prime number.
  • In this example, the main document spawns a worker whose only task is to listen for notifications from the server, and, when appropriate, either add or remove data from the client-side database.
  • In this example, the main document uses two workers, one for fetching stock updates for at regular intervals, and one for fetching performing search queries that the user requests.
  • In this example, multiple windows (viewers) can be opened that are all viewing the same map. All the windows share the same map information, with a single worker coordinating all the viewers. Each viewer can move around independently, but if they set any data on the map, all the viewers are updated.
  • With multicore CPUs becoming prevalent, one way to obtain better performance is to split computationally expensive tasks amongst multiple workers. In this example, a computationally expensive task that is to be performed for every number from 1 to 10,000,000 is farmed out to ten subworkers.
  • offload all the crypto work onto subworkers.

Apparently, this support is also part of Thunderbird, as well. Active background JavaScript threading in my email reader! Zounds!

No comments:

Post a Comment