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

smu*_*kes 15 javascript electron

如果我制作电子应用程序,我很难用谷歌搜索我将如何进行多线程.是网络工作者吗?

Vad*_*gon 21

在渲染器过程中,您可以创建Web Workers,并且这些将在他们自己的线程中运行,但是在这些Web Workers中将禁用节点集成,因为Node不是线程安全的.因此,如果您想在使用Node的单独线程中运行某些东西,那么您将需要生成一个单独的进程,您可以child_process.fork()使用该进程与新进程进行通信send().


Ter*_*nce 13

关于电子,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);
}
Run Code Online (Sandbox Code Playgroud)

感谢如何创造加快您的应用程序使Node.js的集群.例如.

电子特定概念

回到Electron还有一些值得注意的其他概念.Electron中的过程是独一无二的,因为它们有两种口味.

**渲染过程** - 包含网页的过程.与典型的网页一样,这些进程在沙箱中创建.

**主要流程** - 引导您的应用程序的过程.它创建渲染过程及其网页.它还可以通过rpc充当所有衍生渲染过程的通信中心.

这是Electron Tutorial中样本的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;
  });
});
Run Code Online (Sandbox Code Playgroud)

TL; DR;

Node.js中不存在线程,而电子是基于Node.js\io.js和Chromium构建的框架.Electron的基础是Node.js. 您可以在node.js中使用分叉生成子进程.