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);
}
}
And I call removeConnection when a request is closed:
req.on('close', function () {
console.log("connection closed");
removeConnection(res);
});
I wonder if the above code is thread safe? I mean as Node.js is event driven, is the followinf scenario possible?
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?
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.
So your code (and all Node.js code) is by definition thread-safe.