Javascript Node.js 和互斥锁
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5481675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js and Mutexes
提问by mellowsoon
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?
我想知道 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.
我了解 Javascript(因此 Node.js)是单线程的。我只是不清楚事件是如何处理的。事件会中断吗?如果是这种情况,我的应用程序可能正在读取数组,被中断以运行更改数组的事件回调,然后继续处理现在已被事件回调更改的数组。
采纳答案by DTrejo
I'm wondering if mutexes/locks are required for data access within Node.js.
我想知道 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.
不!事件在没有其他代码运行时被处理,这意味着不会有争用,因为只有当前运行的代码才能访问该内部数组。作为单线程节点的副作用,长时间计算将阻塞所有其他事件,直到计算完成。
I understand Javascript (and thus Node.js) is single threaded. I'm just not clear on how events are handled. Do events interrupt?
我了解 Javascript(因此 Node.js)是单线程的。我只是不清楚事件是如何处理的。事件会中断吗?
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.
不,事件不会中断。例如,如果您将 awhile(true){}
放入您的代码中,它将停止执行任何其他代码,因为始终有另一个循环迭代要运行。
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).
如果你有一个长时间运行的计算,最好使用process.nextTick,因为这将允许它在没有其他东西运行时运行(我对此很模糊:下面的例子表明我可能它可能不间断地运行)。
If you have any other questions, feel free to stop into #node.jsand ask questions. Also, I asked a couple people to look at this and make sure I'm not totally wrong ;)
如果您有任何其他问题,请随时进入#node.js并提出问题。另外,我让几个人看看这个,确保我没有完全错;)
var count = 0;
var numIterations = 100;
while(numIterations--) {
process.nextTick(function() {
count = count + 1;
});
}
setTimeout(function() {
console.log(count);
}, 2);
//
//=> 100
//
Thanks to AAA_awright of #node.js :)
感谢#node.js 的 AAA_awright :)
回答by Alberto La Rocca
Locks and mutexes areindeed necessary sometimes, even if Node.js is single-threaded.
锁和互斥是确实是必要的,有时,即使Node.js的是单线程的。
Suppose you have two files that must have the same content and not having the same content is considered an inconsistent state. Now suppose you need to change them without blocking the server. If you do this:
假设您有两个文件必须具有相同的内容,并且没有相同的内容被认为是不一致的状态。现在假设您需要在不阻塞服务器的情况下更改它们。如果你这样做:
fs.writeFile('file1', 'content', function (error) {
if (error) {
// ...
} else {
fs.writeFile('file2', 'content', function (error) {
if (error) {
// ...
} else {
// ready to continue
}
});
}
});
you fall in an inconsistent state between the two calls, when another function in the same script may be able to read the two files.
您在两次调用之间处于不一致状态,此时同一脚本中的另一个函数可能能够读取这两个文件。
The rwlockmodule is perfect to handle these cases.
该rwlock中模块完美地处理这些情况。
回答by bobef
I was looking for solution for node mutexes. Mutexes are sometimes necessary - you could be running multiple instances of your node application and may want to assure that only one of them is doing some particular thing. All solutions I could find were either not cross-process or depending on redis.
我正在寻找节点互斥锁的解决方案。互斥体有时是必要的 - 您可能正在运行节点应用程序的多个实例,并且可能想要确保只有其中一个在做某些特定的事情。我能找到的所有解决方案要么不是跨进程的,要么取决于 redis。
So I made my own solution using file locks: https://github.com/Perennials/mutex-node
所以我使用文件锁做了我自己的解决方案:https: //github.com/Perennials/mutex-node
回答by leitning
Mutexes are definitely necessary for a lot of back end implementations. Consider a class where you need to maintain synchronicity of async execution by constructing a promise chain.
对于很多后端实现来说,互斥锁绝对是必要的。考虑一个类,您需要通过构建承诺链来保持异步执行的同步性。
let _ = new WeakMap();
class Foobar {
constructor() {
_.set(this, { pc : Promise.resolve() } );
}
doSomething(x) {
return new Promise( (resolve,reject) => {
_.get(this).pc = _.get(this).pc.then( () => {
y = some value gotten asynchronously
resolve(y);
})
})
}
}
How can you be sure that a promise is not left dangling via race condition? It's frustrating that node hasn't made mutexes native since javascript is so inherently asynchronous and bringing third party modules into the process space is always a security risk.
你怎么能确定一个承诺不会因为竞争条件而悬而未决?令人沮丧的是,节点没有使互斥体成为本机,因为 javascript 本质上是异步的,并且将第三方模块带入进程空间总是存在安全风险。