Web Workers - do they create actual threads?

房东的猫 提交于 2019-12-10 03:07:13

问题


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!


回答1:


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.




回答2:


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.




回答3:


According to MDN,

Web Workers are a mechanism by which a script operation can be made to run in a background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.

So, each worker does not create a separate thread, but all workers are running in a single separate thread.

I guess, like just in other things, the implementation and approach may differ from browser to browser.



来源:https://stackoverflow.com/questions/33776530/web-workers-do-they-create-actual-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!