JavaScript multithreading

Chris Hasiński picture Chris Hasiński · Oct 3, 2011 · Viewed 20.7k times · Source

I'm working on comparison for several different methods of implementing (real or fake) multithreading in JavaScript. As far as I know only webworkers and Google Gears WorkerPool can give you real threads (ie. spread across multiple processors with real parallel execution). I've found the following methods:

  • switch between tasks using yield()

  • use setInterval() (or other non-blocking function) with threads waiting one for another

  • use Google Gears WorkerPool threads (with a plugin)

  • use html5 web workers

I read related questions and found several variations of the above methods, but most of those questions are old, so there might be a few new ideas.

I'm wondering - how else can you achieve multithreading in JavaScript? Any other important methods?

UPDATE: As pointed out in comments what I really meant was concurrency.

UPDATE 2: I found information that Silverlight + JScript supports multithreading, but I'm unable to verify this.

UPDATE 3: Google deprecated Gears: http://code.google.com/apis/gears/api_workerpool.html

Answer

s4y picture s4y · Oct 7, 2011

Web Workers. They’re a W3C standard (well, a working draft at the moment) for exactly this, and require no plugins:

This specification defines an API that allows Web application authors to spawn background workers running scripts in parallel to their main page.

The specification also discusses spreading workers across multiple cores, for true concurrency (this is handled invisibly by the browser’s JavaScript engine):

With multicore CPUs becoming prevalent, one way to obtain better performance is to split computationally expensive tasks amongst multiple workers. In [one] 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.

yield() and setInterval() only schedule things to happen later, they don’t run concurrently with anything else.