我不是Node程序员,但是我对单线程无阻塞IO模型的工作方式感兴趣。在阅读了理解理解节点事件循环文章之后,我对此感到非常困惑。它给出了该模型的示例:
c.query(
'SELECT SLEEP(20);',
function (err, results, fields) {
if (err) {
throw err;
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<html><head><title>Hello</title></head><body><h1>Return from async DB query</h1></body></html>');
c.end();
}
);
队列:由于只有一个线程而有两个请求A(首先出现)和B(首先出现)时,服务器端程序将首先处理请求A:执行SQL查询是代表I / O等待的sleeping语句。并且该程序被困在I/O
等待中,并且无法执行使网页落后的代码。程序在等待期间会切换到请求B吗?我认为,由于是单线程模型,因此无法将一个请求与另一个请求进行切换。但是示例代码的标题表明,除了您的代码之外,所有其他内容都可以并行运行。
(由于我从没使用过Node,所以我不确定我是否误解了代码。)在等待期间,Node如何将A切换到B?您能否以简单的方式解释Node的单线程无阻塞IO模型?如果您能帮助我,我将不胜感激。:)
Okay, most things should be clear so far... the tricky part is the SQL: if it is not in reality running in another thread or process in it’s entirety, the SQL-execution has to be broken down into individual steps (by an SQL processor made for asynchronous execution!), where the non-blocking ones are executed, and the blocking ones (e.g. the sleep) actually can be transferred to the kernel (as an alarm interrupt/event) and put on the event list for the main loop.
That means, e.g. the interpretation of the SQL, etc. is done immediately, but during the wait (stored as an event to come in the future by the kernel in some kqueue, epoll, ... structure; together with the other IO operations) the main loop can do other things and eventually check if something happened of those IOs and waits.
So, to rephrase it again: the program is never (allowed to get) stuck, sleeping calls are never executed. Their duty is done by the kernel (write something, wait for something to come over the network, waiting for time to elapse) or another thread or process. – The Node process checks if at least one of those duties is finished by the kernel in the only blocking call to the OS once in each event-loop-cycle. That point is reached, when everything non-blocking is done.
Clear? :-)
I don’t know Node. But where does the c.query come from?