在Gnu / Linux CentOS上使用nodejs 8.12。对于一个简单的应用程序,使用内置的Web服务器require('https')。
我知道nodejs是单线程的(单进程),并且没有实际的并行代码执行。根据我的理解,我认为http / https服务器将处理一个http请求,并通过所有同步语句运行处理程序,并设置异步语句以稍后执行,然后再返回以处理后续请求。但是,对于http / https库,您具有用于汇编请求主体的异步代码。因此,我们已经有一个在主体准备就绪时执行的回调(“ end”事件)。这个事实使我认为可能有可能同时处理两个或多个请求。
作为处理请求的一部分,我需要执行一串shell命令,并使用shelljs.exec库来执行该操作。它同步运行,等到完成再返回。因此,示例代码如下所示:
const shelljs_exec = require('shelljs.exec');
function process() {
// bunch of shell commands in string
var command_str = 'command1; command2; command3';
var exec_results = shelljs_exec(command_str);
console.log('just executed shelljs_exec command');
var proc_results = process_results(exec_results);
console.log(proc_results);
// and return the response...
}
因此,node.js运行shelljs_exec()并等待完成。在等待期间,是否可以处理另一个请求,从而使同时运行两个或多个shelljs.exec调用存在轻微风险?由于这可能是一个问题,因此我需要确保在给定的时间只能执行一个shelljs.exec语句。
如果这不是正确的理解,那么我想我需要使用互斥锁进行某些操作。像这样:
const shelljs_exec = require('shelljs.exec');
const locks = require('locks');
// Need this in global scope - so we are all dealing with the same one.
var mutex = locks.createMutex();
function await_lock(shell_commands) {
var commands = shell_commands;
return new Promise(getting_lock => {
mutex.lock(got_lock_and_execute);
});
function got_lock_and_execute() {
var exec_results = shelljs_exec(commands);
console.log('just executed shelljs_exec command');
mutex.unlock();
return exec_results;
}
}
async function process() {
// bunch of shell commands in string
var command_str = 'command1; command2; command3';
exec_results = await await_lock(command_str);
var proc_results = process_results(exec_results);
console.log(proc_results);
}
答案 0 :(得分:0)
如果shelljs_exec
是同步的,则不需要。
如果不是。如果需要回调,则将其包装在Promise构造函数中,以便等待它。我建议正确地将mutex.lock
包装在一个诺言中,该诺言将在获得锁后得到解决。如果mutex
引发异常,则需要尝试最后一次以确保shelljs_exec
被解锁。
async function await_lock(shell_commands) {
await (new Promise(function(resolve, reject) {
mutex.lock(resolve);
}));
try {
let exec_results = await shelljs_exec(commands);
return exec_results;
} finally {
mutex.unlock();
}
}
未经测试。但是看起来应该可以。