Web Workers - 他们创建实际的线程吗?

Web Workers - do they create actual threads?

我一直认为 web workers 创建单独的线程,但今天我 运行 进入了 w3c 网站上的规范。以下是关于网络工作者的引用:

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

问题是 - 如果它是 类线程,而不是实际线程,那么使用此技术的优势(性能方面)是什么?

任何帮助将不胜感激!

根据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.

因此,每个工作人员不会创建一个单独的线程,但所有工作人员都运行在一个单独的线程中。

我想,就像其他事情一样,实现和方法可能因浏览器而异。

网络工作者 运行 在与主线程隔离的单个线程中,它们传递消息的方式是 线程式的 并且工作方式不同取决于是否您正在使用专用(只能从创建它的脚本访问)或共享(可以通过端口对象由同一域内的任何脚本访问)工作人员。

编辑: 更新了答案以反映我几个月前的评论。虽然单个 web worker 运行s 在一个独立的线程中,但这并不意味着每个额外的 worker 将 运行 在同一个线程中。

是的,网络工作者创建实际的线程(或进程,规范对此很灵活)。根据Web Workers规范,创建worker的第一步是:

  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)

所以明确规定代码运行ning in Web Workers 运行在实际的线程或进程中

尽管可以在不支持线程的系统上实现不带线程的 Worker(注意 "equivalent construct" 语言),但所有浏览器实现都将 Web Worker 作为线程实现。