电子框架是否允许网络工作者进行多线程处理

Does the electron framework allow multi-threading through web workers?

本文关键字:网络 工作者 多线程处理 框架 是否 许网络      更新时间:2023-09-26

如果我制作了一个电子应用程序,我很难在谷歌上搜索如何进行多线程处理。会是网络工作者吗?

在渲染器过程中,您可以创建Web Worker,这些Web Worker将在自己的线程中运行,但是,由于节点不是线程安全的,因此这些Web Workers中的节点集成将被禁用。因此,如果您想在使用Node的单独线程中运行一些东西,那么您需要生成一个单独的进程,您可以使用child_process.fork()执行此操作,然后使用send()与新进程通信。

关于Electron、Node.js和进程

Electron的工作原理与Node相同。在Node.js中,线程不是原子执行单元。您在事件循环中工作,默认情况下执行是异步的。请参阅此处了解详细信息。话虽如此,您可以通过分叉Node.js中的多个子进程来旋转它们。

下面是一个例子。

//forking a process using cluster
var cluster = require('cluster');
var http = require('http');
var numCPUs = 4;
if (cluster.isMaster) {
    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }
} else {
    http.createServer(function(req, res) {
        res.writeHead(200);
        res.end('process ' + process.pid + ' says hello!');
    }).listen(8000);
}

这要归功于如何创建Node.js集群来加速你的应用程序。

电子特定概念

回到Electron,还有几个额外的概念需要注意。电子工艺的独特之处在于它们有两种风格。

渲染进程-包含网页的进程。这些进程是在沙盒中创建的,就像典型的网页一样。

主进程-引导应用程序的进程。它创建渲染进程及其网页。它还可以充当通过rpc生成的所有渲染进程的通信集线器。

这是Electron教程中样本的main.js部分。这是调用浏览器窗口的主要过程。特别注意mainWindow变量。

'use strict';
const electron = require('electron');
const app = electron.app;  // Module to control application life.
const BrowserWindow = electron.BrowserWindow;  // Module to create native browser window.
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', function() {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform != 'darwin') {
    app.quit();
  }
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600});
  // and load the index.html of the app.
  mainWindow.loadURL('file://' + __dirname + '/index.html');
  // Open the DevTools.
  mainWindow.webContents.openDevTools();
  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
});

TL;DR:

Node.js中不存在线程,Electron是基于Node.js''io.js和Chromium构建的框架。Electron的基础是Node.js。您可以在Node.js中通过分叉生成子进程。

根据多线程文档:

使用Web Worker,可以在操作系统级别的线程中运行JavaScript。

Node的所有内置模块都受支持,但Electron的任何内置模块或具有本地绑定的模块都不应在Web Worker中使用,因为它们不是为线程安全而设计的。

检查电子边缘。它使您能够在单个进程中运行.NET代码和node.js(不需要IPC,性能更好)。这意味着您可以利用node.js.的单线程性来利用.NET的多线程模型

它将在Linux、Mac和Windows上运行,这要归功于.NET Core。

https://github.com/kexplo/electron-edge