Node.js and Mutexes

后端 未结 4 882
情深已故
情深已故 2020-12-25 10:51

I\'m wondering if mutexes/locks are required for data access within Node.js. For example, lets say I\'ve created a simple server. The server provides a couple protocol metho

4条回答
  •  执笔经年
    2020-12-25 11:44

    Locks and mutexes are indeed necessary sometimes, even if Node.js is single-threaded.

    Suppose you have two files that must have the same content and not having the same content is considered an inconsistent state. Now suppose you need to change them without blocking the server. If you do this:

    fs.writeFile('file1', 'content', function (error) {
        if (error) {
            // ...
        } else {
            fs.writeFile('file2', 'content', function (error) {
                if (error) {
                    // ...
                } else {
                    // ready to continue
                }
            });
        }
    });
    

    you fall in an inconsistent state between the two calls, when another function in the same script may be able to read the two files.

    The rwlock module is perfect to handle these cases.

提交回复
热议问题