Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js array slice operation is "thread safe"?

I have a simple websocket chat server which handles multi clients. I use an array to keep track of all clients and slice the array when a client closes the connection.

I was wondering when multiple clients close connections at about the same time, will slicing the array cause problem.

Here is the code segment:

var clients = []; 
var wsServer = new webSocketServer ({
    httpServer: httpserver
});

wsServer.on('request', function(request) {
    var connection = request.accept(null, request.origin);
    var index = clients.push(connection) - 1;

....

connection.on('close', function(connection) {
    for (var i=0; i<clients.length; i++) 
        if (i != index) clients[i].sendUTF('Some client has left the chat!');

    //At this point some other clients may have disconnected and the above 
    //for-loop may be running for another connection.

   clients.splice(index, 1);

   //After the array has been sliced, will the for-loop for other 
   //connection(s) fail?
like image 483
user1941319 Avatar asked Sep 09 '26 13:09

user1941319


1 Answers

Javascript is single threaded, so yes, Array.splice is thread safe.

Async callbacks can only enter the call stack, when the call stack is empty. So, if there is an Array.splice on the call stack, the other callback containing an Array.splice will have to wait until the first one is done.

const arr = [1,2,3,4];
request('http://foo.com', (err, res, body) => {
   arr.splice(0, 1)
});

request('http://bar.com', (err, res, body) => {
   arr.splice(0, 1)
});

Consider the snippet above. In case those requests finish at the same time (just imagine it for the sake of argument). Then one callback, either foo.com or bar.com will enter the call stack. All the synchronous code inside that callback will be executed (The async call will be executed, but not the callback), and the callback from the other request, cannot be processed until the call stack is empty. So foo.com and bar.com callback can't be processed at the same time.

Javascript is single threaded, it has one call stack, so it can only do one thing a time.

like image 98
Marcos Casagrande Avatar answered Sep 11 '26 02:09

Marcos Casagrande