Node.js和Mutexes [英] Node.js and Mutexes

查看:94
本文介绍了Node.js和Mutexes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Node.js中的数据访问是否需要互斥锁/锁。例如,假设我创建了一个简单的服务器。服务器提供了一些协议方法来添加和删除内部数组。我是否需要使用某种类型的互斥锁来保护内部数组?

I'm wondering if mutexes/locks are required for data access within Node.js. For example, lets say I've created a simple server. The server provides a couple protocol methods to add to and remove from an internal array. Do I need to protect the internal array with some type of mutex?

我理解Javascript(因此Node.js)是单线程的。我不清楚如何处理事件。事件中断吗?如果是这种情况,我的应用程序可能正在读取数组,被中断以运行更改数组的事件回调,然后继续处理现在已被事件回调更改的数组。

I understand Javascript (and thus Node.js) is single threaded. I'm just not clear on how events are handled. Do events interrupt? If that is the case, my app could be in the middle of reading the array, get interrupted to run an event callback which changes the array, and then continue processing the array which has now been changed by the event callback.

推荐答案


我想知道Node.js中的数据访问是否需要互斥锁/锁。

I'm wondering if mutexes/locks are required for data access within Node.js.

没有!在没有其他代码运行的情况下处理事件,这意味着不存在争用,因为只有当前运行的代码才能访问该内部数组。作为单线程节点的副作用,长计算将阻止所有其他事件,直到计算完成。

Nope! Events are handled the moment there's no other code to run, this means there will be no contention, as only the currently running code has access to that internal array. As a side-effect of node being single-threaded, long computations will block all other events until the computation is done.


我理解Javascript (因此Node.js)是单线程的。我不清楚如何处理事件。事件是否中断?

I understand Javascript (and thus Node.js) is single threaded. I'm just not clear on how events are handled. Do events interrupt?

不,事件不会中断。例如,如果将而(true){} 放入代码中,它将阻止执行任何其他代码,因为总是会有另一个循环迭代运行。

Nope, events are not interrupted. For example, if you put a while(true){} into your code, it would stop any other code from being executed, because there is always another iteration of the loop to be run.

如果你有一个长时间运行的计算,最好使用 process.nextTick ,因为这将允许它在没有其他任何东西运行时运行(我对此很模糊:下面的例子显示了我可能是正确的,它可能不间断运行,可能)。

If you have a long-running computation, it is a good idea to use process.nextTick, as this will allow it to be run when nothing else is running (I'm fuzzy on this: the example below shows that I'm probably right about it running uninterrupted, probably).

如果您有任何其他问题,请随时进入#node.js 并提出问题。另外,我让几个人看看这个,并确保我并非完全错误;)

If you have any other questions, feel free to stop into #node.js and ask questions. Also, I asked a couple people to look at this and make sure I'm not totally wrong ;)

var count = 0;

var numIterations = 100;
while(numIterations--) {
  process.nextTick(function() {
    count = count + 1;
  });
}

setTimeout(function() {

  console.log(count);

}, 2);

//
//=> 100
//






感谢AAA_awright #node.js:)


Thanks to AAA_awright of #node.js :)

这篇关于Node.js和Mutexes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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