Can node.js code result in race conditions?

后端 未结 6 1821
小鲜肉
小鲜肉 2020-12-02 23:01

From what I read, race conditions occur when different threads try to change a shared variable, which can result in a value that\'s not possible with any serial order of exe

6条回答
  •  难免孤独
    2020-12-03 00:02

    No. Node.js is free of race conditions that would be caused by context switching; however, you can still write a node.js program where asynchronous events happening in an unexpected order result in an inconsistent state.

    For example, suppose you have two functions. The first sends a message through a WebSocket and, in a callback, saves the reply. The second function deletes all saved replies. Calling the functions in order does not guarantee an empty message list. It is important to consider all possible event orderings when doing asynchronous programming.

    EDIT: Here's some example code

    var messages = [];
    
    ...
    
    io.sockets.on('connection', function (socket) {
        socket.emit('ask', { question: 'How many fish do you have?' });
        socket.on('reply', function (data) {
            messages.push(data);
        });
        ...
        wipe();
    });
    
    function wipe() {
        setTimeout(function() {
            messages = [];
        }, 500);
    }
    

提交回复
热议问题