简体   繁体   English

我应该 require('child_process').spawn('node', ['-e', code]) 运行冗长的操作吗?

[英]Should I do require('child_process').spawn('node', ['-e', code]) to run a lengthy operation?

JavaScript doesn't allow multithreading. JavaScript 不允许多线程。 So I'm wondering if I should use所以我想知道我是否应该使用

const node = require('child_process').spawn('node', ['-e', code]);

Where code is the lengthy operation's code I wish to run.其中code是我希望运行的冗长操作代码。

I've tried it and it does work, the main JS program doesn't remain blocked.我已经尝试过了,它确实有效,主 JS 程序不会保持阻塞。

I can also use node.kill() after a timeout to stop the process.我也可以在超时后使用node.kill()来停止进程。

No, you should not use child_process for node processes (unless you really need the OS to manage a separate process for some reason).不,您不应该将child_process用于节点进程(除非您出于某种原因确实需要操作系统来管理单独的进程)。

To run CPU-intensive JavaScript code without blocking, use worker threads .要在不阻塞的情况下运行 CPU 密集型 JavaScript 代码,请使用工作线程 They have less overhead, simpler communication, and may share memory.它们的开销更少,通信更简单,并且可以共享 memory。

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

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