How to write thread safe code in node.js

javascript, multithreading, node.js

Solution

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.

Problem

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? - 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] 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?

Original source