nodejs多线程,fork和Worker

一、前言

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

二、Worker(‘worker_threads’模块)

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

例如(例子为ts):

主进程中:

// 当前为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()

子进程中:

// 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):

主线程:

// 当前为 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!');

       子进程:

// 当前为 test33.ts 文件 子进程

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

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

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值