Web Workers - Do They Create Actual Threads?

I always thought that web workers create separate threads, but today I came across a spec on the w3c website. The following is a link to web workers:

This allows you to perform a thread-like operation with the transmission of messages as a coordination mechanism.

Question: if it is stream -like rather than the actual stream, what is the advantage (in terms of performance) of using this technology?

Any help would be appreciated!

+5
source share
3 answers

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

  • Create a separate parallel runtime (i.e. a separate thread or process or equivalent construct) and follow the remaining steps in this context.

    For the purpose of time APIs, this is the official moment of creating the worker.

(W3C Web Workers 4.4 section)

Thus, it is explicitly stated that the code executed in Web Workers is executed in real threads or processes.

Although you can use Workers without threads (note the language of "equivalent construction") for use on systems that do not support threads, all browser implementations implement web workers as threads.

+2
source

The web worker works in one thread, isolated from the main thread, the way they send messages is thread-like and works differently depending on whether you use a dedicated one (you can only access it from the script created by it) or shared (which can be accessed by any script within the same domain through the port object).

EDIT: Updated answer to reflect my comment from a few months ago. As long as the SINGLE web worker is in an isolated thread, this does not mean that each additional worker will be in the same thread.

+1
source

According to MDN ,

Web Workers is a mechanism by which you can execute a script operation to run in the background thread separately from the main web application execution thread . The advantage of this is that painstaking processing can be performed in a separate thread, allowing you to start the main (usually UI) thread without blocking / slowing down.

So, each worker does not create a separate thread, but all workers work in one separate thread.

I think that, as in other cases, the implementation and approach may differ from browser to browser.

0
source

Source: https://habr.com/ru/post/1236219/


All Articles