一次只允许一个异步操作 [英] Allowing only one async operation at a time
问题描述
我正在构建一个站点,一个特定的操作会触发一个长的服务器端进程来运行。此操作不能同时运行两次,因此我需要实现某种保护。它也不能同步,因为服务器在运行时需要继续响应其他请求。
I'm building a site and one particular operation triggers a long, server-side process to run. This operation can't be run twice at the same time, so I need to implement some sort of protection. It also can't be made synchronous, because the server needs to continue responding to other requests while it runs.
为此,我构建了这个小概念测试,使用 sleep 5
代替我实际的长期运行流程(需要 express 和 child-process-promise ,在具有 sleep
命令的系统上运行,但替换为Windows的任何内容):
To that end I've constructed this small concept test, using sleep 5
as a substitute for my actual long-running process (requires express and child-process-promise, runs on a system with a sleep
command but substitute whatever 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);
这意味着当请求/ test时它会触发一个长操作,如果 / test在运行时再次被请求,它以忙回复并且什么都不做。
The intention of this is when "/test" is requested it triggers a long operation, and if "/test" is requested again while it is running, it replies with "busy" and does nothing.
我的问题是,这个实现安全且正确吗?它似乎在我的粗略测试中起作用,但它很可疑。这是基本上实现互斥+ +try-lock操作的正确方法,还是有一些更合适的Node.js构造?从习惯于标准多线程实践的语言开始,我对
My question is, is this implementation safe and correct? It appears to work in my cursory tests but it's suspiciously simple. Is this the proper way to essentially implement a mutex + a "try-lock" operation, or is there some more appropriate Node.js construct? Coming from languages where I'm used to standard multithreading practices, I'm not quite comfortable with Node's single-threaded-but-asynchronous nature yet.
推荐答案
你很好 - Javascript代码无法与Node中的其他JS代码同时运行。什么都不会改变你下面的忙碌旗帜。无需多线程样式的监视器或关键部分。
You're fine - Javascript code can't run concurrently with other JS code in Node. Nothing will change the busy flag out from under you. No need for multithreaded-styled monitors or critical sections.
这篇关于一次只允许一个异步操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!