Gavriel
Gavriel

Reputation: 19237

How to write thread safe code in node.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);
    }
}

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 following scenario possible?

  1. connections is [a,b,c]
  2. threadB calls removeConnection
  3. in threadB.removeConnection: i = 1
  4. threadA calls removeConnection
  5. in threadA.removeConnection: i = 0
  6. in threadA.removeConnection: connections.splice(0, 1); => connections is [b,c]
  7. in threadA.removeConnection: connections.splice(1, 1); => connections is [b]

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?

Upvotes: 3

Views: 3654

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

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.

Upvotes: 9

Related Questions