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
Multithreading in JavaScript is the real right now. You can offload your work into multiple threads and share memory between them.
In the context of programming, Parallelism is the utilization of multiple threads in an operating system. Routines are able to run at the same time regardless of execution order. JavaScript, however, is single threaded and only one line of code can be executed at any given time.
JS in browsers doesn't support multithreading in the event loop as it is not needed for 99.999% of the websites. The event loop handles everything seamlessly. For the remaining apps, devs can use web workers. Web Workers are a simple means for web content to run scripts in background threads.
JavaScript is a single-threaded language and, at the same time, also non-blocking, asynchronous and concurrent. This article will explain to you how it happens.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With