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.
source share