Skip to main content

Multithreading多线程

With Web Workers, it is possible to run JavaScript in OS-level threads.使用Web Workers,可以在操作系统级线程中运行JavaScript。

Multi-threaded Node.js多线程Node.js

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

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

The nodeIntegrationInWorker can be used independent of nodeIntegration, but sandbox must not be set to true.nodeIntegrationInWorker可以独立于nodeIntegration使用,但sandbox不能设置为true

Available APIs可用的API

All built-in modules of Node.js are supported in Web Workers, and asar archives can still be read with Node.js APIs. Web Workers支持Node.js的所有内置模块,并且仍然可以使用Node.js API读取asar存档。However none of Electron's built-in modules can be used in a multi-threaded environment.然而,Electron的内置模块都不能在多线程环境中使用。

Native Node.js modules原生Node.js模块

Any native Node.js module can be loaded directly in Web Workers, but it is strongly recommended not to do so. 任何本机Node.js模块都可以直接加载到Web Workers中,但强烈建议不要这样做。Most existing native modules have been written assuming single-threaded environment, using them in Web Workers will lead to crashes and memory corruptions.大多数现有的本机模块都是在假设单线程环境下编写的,在Web Workers中使用它们将导致崩溃和内存损坏。

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.请注意,即使本机Node.js模块是线程安全的,将其加载到Web工作器中仍然不安全,因为processdlopen函数不是线程安全的。

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.目前安全加载本机模块的唯一方法是确保在Web工作程序启动后,应用程序不会加载本机的模块。

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