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 Workers 中使用 Node.js 功能,为此,nodeIntegrationInWorker 选项应设置为 webPreferences 中的 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.

注意:由于沙盒策略不兼容,该选项在 SharedWorkerService Worker 中不可用。

¥Note: This option is not available in SharedWorkers or Service Workers owing to incompatibilities in sandboxing policies.

可用的 API

¥Available APIs

Web Workers 支持 Node.js 的所有内置模块,并且仍然可以使用 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 Workers 启动后不加载原生模块。

¥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')