网站不兼容怎么办,微分销商城,长沙全程网络营销哪家便宜,北京专业做网站电话一、前言 javascript是单线程执行的#xff0c;如果想要多线程执行#xff0c;那么相当于再运行一个node,其实不该理解成多线程#xff0c;更像是多进程。
二、Worker(‘worker_threads’模块) worker有点类似exec#xff0c;直接再cmd执行node命令#xff0c;不同的是两…一、前言 javascript是单线程执行的如果想要多线程执行那么相当于再运行一个node,其实不该理解成多线程更像是多进程。
二、Worker(‘worker_threads’模块) worker有点类似exec直接再cmd执行node命令不同的是两个node进程之间可以通过发送消息的方式进行通信。
例如(例子为ts)
主进程中
// 当前为test2.ts 文件
import {Worker, isMainThread} from worker_threadsasync function runWork():Promisevoid{// 当前是主线程if(isMainThread){//const log execSync(ts-node ./test.ts,{cwd:__dirname}).toString()// 运行子线程--相当于输入node-ts ./test.tsconst 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_threadsrequire(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_processrequire(child_process)
// 向父进程发送消息
if(typeof process.send!undefined){process.send(你们好主进程);
}总结nodejs的多线程不像java那样它更像是运行了多个node