gpt4 book ai didi

node.js - NodeJS 中的多线程与 fork 进程

转载 作者:搜寻专家 更新时间:2023-10-31 23:25:59 25 4
gpt4 key购买 nike

我试图找到一种更好的方法来使用 NodeJS 运行一些 CPU 绑定(bind)任务。据我所知,有 2 个选项,fork processesworker threads .所以我在它们之间运行了一个基准测试,发现 fork 进程更快。

所以,我有一些问题:

  1. 为什么 fork process 方法更快?
  2. 工作线程没用吗?或者工作线程的优势是什么,消耗更少的 cpu/内存?

我正在使用 Node v10.15.3 在 MacOS(2.2 GHz Intel Core i7、16 GB 1600 MHz DDR3)上运行代码

基准代码在我的gist中:

线程池库 microjob和进程池库node-worker-farm如您所见,在我的代码中使用。运行的命令是:node --experimental-worker benchmark.js

最佳答案

我认为@gireeshpunathil 的评论来自 https://github.com/nodejs/help/issues/1920可以帮上大忙:

there is no single formulae that computes which method will be faster. It depends on a number of parameters:

  • the running time of the job itself
  • the interaction of the job with the spawning code
  • the machine characteristics, specifically cpu, memory and scheduling

the fork uses native fork and exec, that is heavy-weight than thread creation. fork creates a new node instance with new v8, isolate, libuv etc. worker does not create new node instance. forked process uses IPC channel to talk to the forking process, if needed. workers use in-memory buffers.

So:

  • if the execution time of the microjob is too small compared to the process creation, worker method will be faster.
  • if the job communicates with the driver, the frequency of communication and the cost of communication will decide the winner
  • if the job runs as long independent piece of code with no interaction, fork method will eventually prove faster (I think that
    is happening here)

关于node.js - NodeJS 中的多线程与 fork 进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56181096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com