如何在node.js中编写线程安全代码 [英] How to write thread safe code in node.js

查看:145
本文介绍了如何在node.js中编写线程安全代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的app.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);
    }
}

我在请求关闭时调用removeConnection:

And I call removeConnection when a request is closed:

req.on('close', function () {
    console.log("connection closed");
    removeConnection(res);
});

我想知道上面的代码是否是线程安全的?我的意思是Node.js是事件驱动的,可能是以下场景?

I wonder if the above code is thread safe? I mean as Node.js is event driven, is the following scenario possible?


  1. connections是[a,b,c]

  2. threadB调用removeConnection

  3. 在threadB.removeConnection中:i = 1

  4. threadA调用removeConnection
  5. $ b threadA.removeConnection中的$ b
  6. :i = 0

  7. :threadA.removeConnection:connections.splice(0,1); => connections是[b,c]

  8. 在threadA.removeConnection中:connections.splice(1,1); => connections是[b]

  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]

正如您在此场景中看到的那样,将删除threadC的连接而不是threadB的连接。

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?

推荐答案

Node.js的一个关键原则是所有用户代码在单个线程中运行,这使开发人员无需处理编写线程安全代码的复杂性。

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.

所以你的代码(以及所有Node.js代码)根据定义是线程安全的。

So your code (and all Node.js code) is by definition thread-safe.

这篇关于如何在node.js中编写线程安全代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆