简体   繁体   English

node.js中的子/次线程

[英]Child/Secondary thread in node.js

I have a requirement, where I have to run a process independent of the main node thread. 我有一个要求,我必须独立于主节点线程运行一个进程。 Basically, the purpose is to initiate the secondary process from the main node thread data, and not wait for the callback or any result, as the secondary process does not have to give anything back to the main thread. 基本上,目的是从主节点线程数据中启动辅助进程,而不是等待回调或任何结果,因为辅助进程不必将任何东西还给主线程。

I want to achieve this, without blocking the main nodejs thread, and the main thread should not care what happens after it passes the data to the secondary thread. 我想实现这一目标,而不阻塞主nodejs线程,并且主线程不关心将数据传递到辅助线程后会发生什么。 Basically, the process of the main thread ends after sending the data to the secondary thread, as far as secondary process is concerned. 基本上,就次级进程而言,主线程的过程在将数据发送到次级线程之后结束。

Any suggestions how I can achieve this? 有什么建议可以实现这一目标吗? I read about the child process, webworkers, dnode and process nexttick, but I am not sure what is the best way to achieve it. 我读到有关子进程,Webworkers,dnode和进程nexttick的信息,但我不确定实现它的最佳方法是什么。 I tried nexttick, but my experience has been that it still stays the part of the main thread, although asynchronously. 我尝试了nexttick,但是我的经验是,尽管异步,它仍然是主线程的一部分。

If your goal is just to start the process without regard for the output, you should use spawn with detached:true . 如果您的目标只是开始过程而不考虑输出,则应将spawndetached:true

For passing data, you can write using stdin (see the example) or pass command line arguments or write to file and redirect. 对于传递数据,您可以使用stdin进行编写(请参见示例),也可以传递命令行参数,或者写入文件并重定向。

I have implemented child process-fork for passing data for secondary / background processing to a child process (without disconnecting the child process). 我实现了子进程前叉,用于将用于辅助/后台处理的数据传递给子进程(无需断开子进程的连接)。 This seems to be doing my job well as of now. 到目前为止,这似乎很好地完成了我的工作。 I will update if I face any issues or find a better solution. 如果遇到任何问题或找到更好的解决方案,我将进行更新。

//Main Process
var cp = require('child_process').fork('child.js');
cp.send(data);


//Child Process (child.js)
process.on('message', function(data){
 //do something with data
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM