1

In my multiuser live nods.js app, I have a function that removes a specific element from an array. It's an asyn function and can potentially be called by two different users independently and probably at the same time (client-site socket trigger) to perform the operation on the same array.

myUsers= [];
myUsers.push('user1');
myUsers.push('user2');
myUsers.push('user3');

function removeUser(user){
    for(var i=0; i<=myUsers.length; i++){
        if(user===myUsers[i]){
            myUsers.splice(i,1);
            break;
}   }   }

Should I be worried that it might lead to removing the wrong/unintended element as a result of both operations happening simultaneously? Like, when removeUser('user1') and removeUser('user3') are both called at the same time (client-site socket trigger), and while user1 is being spliced, and user3 has reached at i=2 it might remove user2 instead of user3? And i might even now go over the loop's original limit (myUsers.length)?

Is my concern valid? If so, what would be the solution?

Community
  • 1
  • 1
laggingreflex
  • 26,275
  • 28
  • 123
  • 172

1 Answers1

1

No. Node.js is single threaded. So, only one function will be executed at a time. The problem you describe is specific to multi-threaded environments only.

For example, though removeUser('user1') and removeUser('user3') are ready to be executed, they will be pushed in a queue. And the Node.js engine will take the element at the front and executes it and once finishes executing that, picks the next item from the queue. So, user1 will be removed first and then user3.

thefourtheye
  • 206,604
  • 43
  • 412
  • 459