nodejs多线程,fork和Worker

一、前言

javascript是单线程执行的,如果想要多线程执行,那么相当于再运行一个node,其实不该理解成多线程,更像是多进程。

二、Worker('worker_threads'模块)

worker有点类似exec,直接再cmd执行node命令,不同的是两个node进程之间可以通过发送消息的方式进行通信。

例如(例子为ts):

主进程中:

javascript 复制代码
// 当前为test2.ts 文件
import {Worker, isMainThread} from 'worker_threads'

async function  runWork():Promise<void>{
    // 当前是主线程
    if(isMainThread){
          //const log= execSync("ts-node ./test.ts",{cwd:__dirname}).toString()
        // 运行子线程--相当于输入node-ts  ./test.ts
        const woker =new Worker("./test.ts",{workerData:"hello"}) 
        // 监听事件
        // message 为固定事件 
        // error 事件 子线程的错误信息
        // exit 事件 子线程执行完毕 时候的事件
        woker.on("message",(data:string)=>{
             console.log("主线程接收数据:"+data);
       })
    }
    
    console.log("主线程");
    
}
runWork()

子进程中:

javascript 复制代码
// test.ts文件 注意:子进程不支持ES6语法

const worker_threads=require('worker_threads') 
console.log("线程2,接收数据"+worker_threads.workerData);
// 向主进程发送数据
worker_threads.parentPort.postMessage("hello2")

worker 只能在主进程中创建,不能在子进程中再创建

三、fork(child_process模块)

fork比worker出现得早,于worker相比,它可以在子线程再创建子线程,但是worker更轻量.

例子(ts):

主线程:

javascript 复制代码
// 当前为 test3.ts文件 主进程

// 引入模块
const { fork } = require('child_process');

// 创建子进程
const child = fork('test33.ts');

// 监听子进程发送的消息
child.on('message', (data:string) => {
   
        console.log("接收的消息:"+data);
    

});

// 向子进程发送消息
child.send('Hello from parent process!');

子进程:

javascript 复制代码
// 当前为 test33.ts 文件 子进程

const child_process=require("child_process")
// 向父进程发送消息
if(typeof process.send!='undefined'){
    process.send('你们好主进程');
}

总结:nodejs的多线程不像java那样,它更像是运行了多个node

相关推荐
佟格湾11 小时前
聊透多线程编程-线程互斥与同步-12. C# Monitor类实现线程互斥
c#·多线程
佟格湾16 小时前
聊透多线程编程-线程互斥与同步-13. C# Mutex类实现线程互斥
c#·多线程
佟格湾1 天前
聊透多线程编程-线程互斥与同步-11. C# lock关键字实现线程互斥
c#·多线程
GOTXX7 天前
【Qt】Qt 信号与槽机制全解析
开发语言·数据库·c++·qt·多线程·用户界面
FreakStudio7 天前
一文速通 Python 并行计算:07 Python 多线程编程-线程池的使用和多线程的性能评估
python·单片机·嵌入式·多线程·面向对象·并行计算·电子diy
杨某一辰8 天前
库magnet使用指南
c++·多线程·
beyond谚语9 天前
七、Qt框架编写的多线程应用程序
c++·qt·多线程·定时器
佟格湾9 天前
聊透多线程编程-线程池-7.C# 三个Timer类
开发语言·后端·c#·多线程编程·多线程
码熔burning10 天前
ReentrantLock 实现公平锁和非公平锁的原理!
多线程··reentrantlock
佟格湾10 天前
聊透多线程编程-线程池-6.C# APM(异步编程模型)
开发语言·后端·c#·多线程