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 anotheruse 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
Web Workers. They’re a W3C standard (well, a working draft at the moment) for exactly this, and require no plugins:
The specification also discusses spreading workers across multiple cores, for true concurrency (this is handled invisibly by the browser’s JavaScript engine):
yield()
andsetInterval()
only schedule things to happen later, they don’t run concurrently with anything else.q: how else can you achieve concurrency in Javascript
You can use async or 'non-blocking' type methods. This has one of the major buzzes about the node.js system. It's not exactly multithreaded, but it does tend to be faster.
Multithread.js is a library for really easy multithreading in JS that wraps Web Workers and does the majority of your work for you. :)
There is no direct support for multithreading in JavaScript. However you can achieve this by applying some ideas and method.
There are methods like:
here the JavaScript code is called after the specifed time and we can use
for clearing. By this we can achieve fake concurrency.
You can have your code transformed into JavaScript code that doesn't have any explicit loops or direct function calls, instead code is divided into small units of execution that are managed by a threading engine. In my example code I show how a function with loops would be transformed but I've omitted the mechanism for function calls just to keep the example simple.
The process of transformation basically works by splitting code at division points. These division points are function calls and loops (as demonstrated above). In the example I've used objects and keys but it may be much easier on the browser's JavaScript engines if the units stored the stack as an object variable (i.e. storing using
this.foo = bar
instead ofstack["foo"] = bar
).For example the following code:
... into something like this: