Skip to main content

多线程

🌐 Multithreading

使用 网页工作线程,可以在操作系统级线程中运行 JavaScript。

🌐 With Web Workers, it is possible to run JavaScript in OS-level threads.

多线程 Node.js

🌐 Multi-threaded Node.js

可以在 Electron 的 Web Worker 中使用 Node.js 功能,要做到这一点,需要在 webPreferences 中将 nodeIntegrationInWorker 选项设置为 true

🌐 It is possible to use Node.js features in Electron's Web Workers, to do so the nodeIntegrationInWorker option should be set to true in webPreferences.

const win = new BrowserWindow({
webPreferences: {
nodeIntegrationInWorker: true
}
})

nodeIntegrationInWorker 可以独立于 nodeIntegration 使用,但 sandbox 不得设置为 true

🌐 The nodeIntegrationInWorker can be used independent of nodeIntegration, but sandbox must not be set to true.

note

由于沙箱策略的不兼容,此选项在 SharedWorkerService Worker 中不可用。

可用的 API

🌐 Available APIs

Node.js 的所有内置模块在 Web Workers 中都受到支持,并且仍然可以使用 Node.js API 读取 asar 存档。然而,Electron 的内置模块在多线程环境中无法使用。

🌐 All built-in modules of Node.js are supported in Web Workers, and asar archives can still be read with Node.js APIs. However none of Electron's built-in modules can be used in a multi-threaded environment.

原生 Node.js 模块

🌐 Native Node.js modules

任何原生 Node.js 模块都可以直接在 Web Workers 中加载,但强烈不建议这样做。大多数现有的原生模块都是假设单线程环境编写的,在 Web Workers 中使用它们可能会导致崩溃和内存损坏。

🌐 Any native Node.js module can be loaded directly in Web Workers, but it is strongly recommended not to do so. Most existing native modules have been written assuming single-threaded environment, using them in Web Workers will lead to crashes and memory corruptions.

请注意,即使原生 Node.js 模块是线程安全的,也仍然不安全在 Web Worker 中加载它,因为 process.dlopen 函数不是线程安全的。

🌐 Note that even if a native Node.js module is thread-safe it's still not safe to load it in a Web Worker because the process.dlopen function is not thread safe.

目前,安全加载本地模块的唯一方法,是确保应用在 Web Worker 启动后不加载任何本地模块。

🌐 The only way to load a native module safely for now, is to make sure the app loads no native modules after the Web Workers get started.

process.dlopen = () => {
throw new Error('Load native module is not safe')
}
const worker = new Worker('script.js')