electron/docs/tutorial/multithreading.md

53 lines
1.8 KiB
Markdown
Raw Normal View History

2017-03-15 10:34:21 +00:00
# Multithreading
With [Web Workers][web-workers], it is possible to run JavaScript in OS-level
threads.
## Multi-threaded Node.js
2017-03-16 08:41:25 +00:00
It is possible to use Node.js features in Electron's Web Workers, to do
2017-03-15 10:34:21 +00:00
so the `nodeIntegrationInWorker` option should be set to `true` in
`webPreferences`.
```javascript
2020-07-09 17:18:49 +00:00
const win = new BrowserWindow({
2017-03-15 10:34:21 +00:00
webPreferences: {
nodeIntegrationInWorker: true
}
})
```
The `nodeIntegrationInWorker` can be used independent of `nodeIntegration`, but
`sandbox` must not be set to `true`.
**Note:** This option is not available in [`SharedWorker`s](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker) or [`Service Worker`s](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker) owing to incompatibilities in sandboxing policies.
2017-03-15 10:34:21 +00:00
## Available APIs
All built-in modules of Node.js are supported in Web Workers, and `asar`
2017-03-16 08:41:25 +00:00
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.
2017-03-15 10:34:21 +00:00
## Native Node.js modules
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
2017-03-16 08:41:25 +00:00
written assuming single-threaded environment, using them in Web Workers will
2017-03-15 10:34:21 +00:00
lead to crashes and memory corruptions.
2017-03-16 08:41:25 +00:00
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.
2017-03-15 10:34:21 +00:00
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.
```javascript
process.dlopen = () => {
throw new Error('Load native module is not safe')
}
2020-07-09 17:18:49 +00:00
const worker = new Worker('script.js')
2017-03-15 10:34:21 +00:00
```
[web-workers]: https://developer.mozilla.org/en/docs/Web/API/Web_Workers_API/Using_web_workers