Node.js 数组切片操作是“线程安全的”吗?

use*_*319 3 websocket node.js

我有一个简单的 websocket 聊天服务器,可以处理多个客户端。我使用一个数组来跟踪所有客户端,并在客户端关闭连接时对数组进行切片。

我想知道当多个客户端大约同时关闭连接时,对数组进行切片是否会导致问题。

这是代码段:

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?
Run Code Online (Sandbox Code Playgroud)

Mar*_*nde 5

JavaScript 是单线程的,所以是的,Array.splice线程安全。

当调用堆栈为空时,异步回调只能进入调用堆栈。因此,如果调用堆栈上有 an Array.splice,则包含 an 的另一个回调Array.splice将必须等待第一个回调完成。

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)
});
Run Code Online (Sandbox Code Playgroud)

考虑上面的片段。如果这些请求同时完成(为了争论,请想象一下)。然后一个回调,或者foo.combar.com将进入调用堆栈。该回调中的所有同步代码都将被执行(异步调用将被执行,但回调不会被执行),并且来自其他请求的回调在调用堆栈为空之前无法被处理。所以 foo.combar.com回调不能同时处理。

JavaScript 是单线程的,它有一个调用栈,所以它一次只能做一件事。

  • 让 Node.js 开发变得超级简单的原因之一是能够安全地知道同步块中的所有内容都是“线程安全的”,并且能够使用回调显式确定任何异步内容的控制流(或者现在更常见的承诺) )。 (2认同)