问题描述
这是我的app.js的一部分:
Here's a part of my app.js:
var connections = [];
function removeConnection(res) {
var i = connections.indexOf(res);
if (i !== -1) {
connections.splice(i, 1);
}
}
我在请求关闭时调用removeConnection:
And I call removeConnection when a request is closed:
req.on('close', function () {
console.log("connection closed");
removeConnection(res);
});
我想知道上面的代码是否是线程安全的?我的意思是Node.js是事件驱动的,可能是以下场景?
I wonder if the above code is thread safe? I mean as Node.js is event driven, is the following scenario possible?
- connections是[a,b,c]
- threadB调用removeConnection
- 在threadB.removeConnection中:i = 1
- threadA调用removeConnection $ b threadA.removeConnection中的$ b
- :i = 0
- :threadA.removeConnection:connections.splice(0,1); => connections是[b,c]
- 在threadA.removeConnection中:connections.splice(1,1); => connections是[b]
- connections is [a,b,c]
- threadB calls removeConnection
- in threadB.removeConnection: i = 1
- threadA calls removeConnection
- in threadA.removeConnection: i = 0
- in threadA.removeConnection: connections.splice(0, 1); => connections is [b,c]
- in threadA.removeConnection: connections.splice(1, 1); => connections is [b]
正如您在此场景中看到的那样,将删除threadC的连接而不是threadB的连接。
As you see in this scenario, threadC's connection would be removed instead of threadB's.
这可能发生吗?如果是,那么我应该如何修复代码?
Can this happen? If yes, then how should I fix the code?
推荐答案
Node.js的一个关键原则是所有用户代码在单个线程中运行,这使开发人员无需处理编写线程安全代码的复杂性。
One of the key principles of Node.js is that all user code runs in a single thread which eliminates the need for the developer to deal with the complexities of writing thread-safe code.
所以你的代码(以及所有Node.js代码)根据定义是线程安全的。
So your code (and all Node.js code) is by definition thread-safe.
这篇关于如何在node.js中编写线程安全代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!