javascript - 无法确定任何并发

标签 javascript node.js

我想在我的控制台上显示并发以检查我是否正确使用了 child_process 库。为此,我得到了这两个模块:

测试.js

const fork = require('child_process').fork;

const child1 = fork('./newModule', ['child1']);
console.log('now1');
const child2 = fork('./newModule', ['child2']);
console.log('now2');

child1.on('message', function(data){
    console.log(data);
});
console.log('now3');
child2.on('message', function(data){
    console.log(data);
});

for (var i = 0; i < 50; i++) {
    console.log(i);
}

新模块.js

(function(cb) {

        for (let i = 0; i < 50; i++) {
            process.send(process.argv[2] + ' ' + i);
        }
        process.exit();

}());

但是我控制台上的输出是:

now1
now2
now3
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
child2 0
child2 1
child2 2
child2 3
child2 4
child2 5
child2 6
child2 7
child2 8
child2 9
child2 10
child2 11
child2 12
child2 13
child2 14
child2 15
child2 16
child2 17
child2 18
child2 19
child2 20
child2 21
child2 22
child2 23
child2 24
child2 25
child2 26
child2 27
child2 28
child2 29
child2 30
child2 31
child2 32
child2 33
child2 34
child2 35
child2 36
child2 37
child2 38
child2 39
child2 40
child2 41
child2 42
child2 43
child2 44
child2 45
child2 46
child2 47
child2 48
child2 49
child1 0
child1 1
child1 2
child1 3
child1 4
child1 5
child1 6
child1 7
child1 8
child1 9
child1 10
child1 11
child1 12
child1 13
child1 14
child1 15
child1 16
child1 17
child1 18
child1 19
child1 20
child1 21
child1 22
child1 23
child1 24
child1 25
child1 26
child1 27
child1 28
child1 29
child1 30
child1 31
child1 32
child1 33
child1 34
child1 35
child1 36
child1 37
child1 38
child1 39
child1 40
child1 41
child1 42
child1 43
child1 44
child1 45
child1 46
child1 47
child1 48
child1 49

相反,我希望有类似的东西:

now1
now2
now3
1
child1 1
child2 1
2
child1 2
child2 2
...

now1
now2
now3
child1 1
child2 1
child1 2
child2 2
...
1
2
...

这是什么原因?没有并发还是我只是显示错误?

最佳答案

当你启动一个 for 循环时,你让进程继续做只是那个而不做其他事情 - 它甚至不允许 Node.js 将消息刷新到父进程,因为 JavaScript 线程(并且只能有一个 JS 线程)正忙于遍历 for 循环。

您在所有进程中执行此操作 - 在父进程和两个子进程中。这意味着在某个地方,在幕后,发送到控制台的消息不能真正发送到父进程或 stdout 流,因为 Node.js 也在 JavaScript 中实现了大量的功能,并且因为该线程是忙于执行 for 循环,它将在该循环的最后执行,立即刷新所有内容。此外,由于您在父进程中执行 for 循环,即使消息确实成功发送到父进程,它们也不会在您的 for 结束之前被处理code> 循环,因为他们会等待 JS 线程变得可用于其他工作。这就是事件循环的工作原理(请参阅下面的链接)。

要防止这种行为,您需要以其他方式重新实现该循环 - 一种允许 Node 在各个迭代之间执行其他工作的方式。

在其他地方有很多教程如何做到这一点。您需要查找的内容是 Node 的 event loop 的总体概述。和 setImmediate() (安排在下一个事件循环中完成的工作)。

关于javascript - 无法确定任何并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52597357/

相关文章:

javascript - 重置 v-model 而不更新其因变量

javascript - 视频静音/取消静音按钮 javaScript

javascript - 如何使用node js在前端显示modgodb中存储的图像URL路径

javascript - "Location " Node/javascript 中的属性

javascript - parseInt 未按预期工作

javascript - 如何使用 JS API 断开 twilio 客户端的连接?

javascript - 尝试从 vue.js 中的 http 请求推送到数组时出错

node.js - Sequelize 连接具有相同外键的两个表

javascript - proxychains 无法加载进程?

node.js - 使用 AWS 时,我应该在哪里上传我的应用程序文件?