Allow only one aync operation at a time

I am creating a website and one specific operation starts a lengthy server process to start. At the same time, this operation cannot be run twice, so I need to implement some kind of protection. It also cannot be made synchronous because the server must continue to respond to other requests at runtime.

To this end, I built this small conceptual test, using sleep 5 as a replacement for my actual long-term process (requires express and child promises, it works on the system with the sleep command, but replace anything for Windows):

 var site = require("express")(); var exec = require("child-process-promise").exec; var busy = false; site.get("/test", function (req, res) { if (busy) { res.json({status:"busy"}); } else { busy = true; // <-- set busy before we start exec("sleep 5").then(function () { res.json({status:"ok"}); }).catch(function (err) { res.json({status:err.message}); }).then(function () { busy = false; // <-- finally: clear busy }); } }); site.listen(8082); 

The purpose of this is to request "/ test", which causes a lengthy operation, and if "/ test" is requested again during its launch, it answers "busy" and does nothing.

My question is, is this implementation safe and correct? It seems to work in my cursory tests, but it is suspiciously simple. Is this a suitable way to essentially implement the mutex + try-lock operation, or is there a more suitable Node.js construct? Based on the languages ​​in which I am used to standard multi-threaded practices, I still do not quite agree with Node's single-threaded, but asynchronous nature.

+6
source share
1 answer

You are fine - Javascript code cannot work simultaneously with other JS code in Node. Nothing will change the employment flag from beneath you. No need for multi-threaded monitors or critical partitions.

+3
source

Source: https://habr.com/ru/post/1013107/


All Articles