Which operations in node are thread safe?

后端 未结 2 1353
难免孤独
难免孤独 2021-02-07 20:19

I\'m using this approach to store data in a global array hosting an http server where certain requests will manipulate the global array.

I\'m kind of worried about runni

相关标签:
2条回答
  • 2021-02-07 21:06

    Raynos is mostly correct. But just because JavaScript is single threaded doesn't mean you can let your guards down. You still need to be aware of threads. A good example to illustrate this is how socket.io is maintaining connection with varies clients and still be able to keep track of these clients.

    JavaScript's functional programming part works by variable binding (like...A LOT). Not being aware of threads makes you falsely assumes that your variables are the correctly bound. Like the socket.io example, how can you be sure the connection you're getting is the client you think you're getting? What if the reference binding went wrong and the connection actually references a different client?

    This is the type of things you need to be careful of.

    0 讨论(0)
  • 2021-02-07 21:12

    All are thread safe.

    There are no threads, JavaScript is single threaded, it's impossible for two javascript statements to run at the same time.

    As an aside, you shouldn't be using globals anyway because globals are evil

    Edit:

    Test 2 fails because you're using asynchronous callbacks, which means control goes back to node and it can handle more requests. This creates race conditions as seen.

    In node, anything that's not asynchronous blocks. The only asynchronous things you have are setTimeout/setInterval/process.nextTick and any asynchronous IO operations.

    One shouldn't manually make computation asychronous. One should just avoid doing too much computation.

    I've written an article about What it means to be non-blocking

    0 讨论(0)
提交回复
热议问题