Which operations in node are thread safe?

后端 未结 2 1352
难免孤独
难免孤独 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: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

提交回复
热议问题