Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Workers - do they create actual threads?

I have always thought that web workers create separate threads, but today I ran into the spec on w3c website. Below is a citation about web workers:

This allows for thread-like operation with message-passing as the coordination mechanism.

The question is - if it is thread-like, not actual thread what is an advantage(performance wise) of using this technology?

Any help will be appreciated!

like image 712
andrey Avatar asked Nov 18 '15 09:11

andrey


2 Answers

Yes, web workers create actual threads (or processes, the spec is flexible on this). According to the Web Workers specification, when a worker is created the first step is:

  1. Create a separate parallel execution environment (i.e. a separate thread or process or equivalent construct), and run the rest of these steps in that context.

    For the purposes of timing APIs, this is the official moment of creation of the worker.

(W3C Web Workers specification section 4.4)

So it is explicitly specified that code running in Web Workers run in actual threads or processes.

Although it is possible to implement Workers without threads (note the "equivalent construct" language) for use on systems that don't support threads, all browser implementations implement Web Workers as threads.

like image 146
slebetman Avatar answered Oct 16 '22 06:10

slebetman


A web worker runs in a single thread isolated from the main thread, the way they pass messages around is thread-like and works differently depending on whether you're using dedicated (can only be accessed from the script that created it) or shared (can be accessed by any script within the same domain via a port object) workers.

EDIT: Updated answer to reflect my comment from months ago. While a SINGLE web worker runs in an isolated thread it doesn't mean each additional worker will run in the same thread.

like image 38
Tim Sheehan Avatar answered Oct 16 '22 06:10

Tim Sheehan