nodejs中的并发模型 [英] Models of concurrency in nodejs

查看:164
本文介绍了nodejs中的并发模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道nodejs中的内存和线程模型?

Does anyone know what the memory and threading models are in nodejs?

特别是 ii ++ ?它在java 1.5中,在Java 1.4中,在C中,或者根本不是? ii volatile

In particular, is ii++ atomic? Does it behave as if ii were volatile in Java 1.5, in Java 1.4, in C, or not at all?

推荐答案

了解节点和V8之间的交互方式非常有用。节点处理等待操作系统中的I / O或计时器。当节点从I / O或定时器唤醒时,它通常有一些JavaScript回调来调用。当节点运行这些回调时,控制被传递到V8,直到V8返回节点。

It is useful to understand how node and V8 interact. Node handles waiting for I/O or timers from the operating system. When node wakes up from I/O or a timer, it generally has some JavaScript callbacks to invoke. When node runs these callbacks, control is passed into V8 until V8 returns back to node.

因此,如果你做 var ii = 1; ii ++; ,你永远不会发现ii是除2之外的任何东西。所有JavaScript运行直到完成,然后控制传递回节点。如果你做 doSomething(); doSomething(); 将始终运行doSomething两次,并且它不会返回到节点的事件循环,直到第二次调用doSomething返回。这意味着你可以从一个简单的错误中完全锁定节点:

So, if you do var ii = 1; ii++;, you will never find that ii is anything other than 2. All JavaScript runs until completion, and then control is passed back to node. If you do doSomething(); doSomething(); that will always run doSomething twice, and it will not return to node's event loop until the second invocation of doSomething returns. This means you can completely lock up node from a simple error like this:

for (var i=0 ; i >= 0 ; i++) {}

这并不是你注册了多少个I / O回调,定时器设置为关闭,或套接字等待读取。直到V8从那个无限循环返回,节点不再工作。

It doesn't mater how many I/O callbacks you have registered, timers set to go off, or sockets waiting to be read. Until V8 returns from that infinite loop, node does no more work.

这是节点中编程的一部分。你永远不必担心锁定。没有种族条件或关键部分。您的JavaScript代码只运行一个线程。

This is part of what makes programming in node so nice. You never have to worry about locking. There are no race conditions or critical sections. There is only one thread where your JavaScript code runs.

这篇关于nodejs中的并发模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆