單線程非阻塞 IO 模型如何在 Node.js 中工作 - How the single threaded non blocking IO model works in Node.js

問題:

I'm not a Node programmer, but I'm interested in how the single threaded non blocking IO model works.我不是 Node 程序員,但我對單線程非阻塞 IO 模型的工作原理很感興趣。 After I read the article understanding-the-node-js-event-loop , I'm really confused about it.在我閱讀了《 understanding-the-node-js-event-loop 》一文後,我真的很困惑。 It gave an example for the model:它給出了模型的示例:

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();
    }
);

Que: When there are two request A(comes first) and B since there is only a single thread, the server-side program will handle the request A firstly: doing SQL querying is asleep statement standing for I/O wait. Que:當有兩個請求A(先來)和B時,因爲只有一個線程,服務器端程序會先處理請求A:做SQL查詢是睡眠語句,代表I/O等待。 And The program is stucked at the I/O waiting, and cannot execute the code which renders the web page behind.並且程序卡在I/O等待上,無法執行渲染網頁的代碼。 Will the program switch to request B during the waiting?程序在等待過程中會切換到請求B嗎? In my opinion, because of the single thread model, there is no way to switch one request from another.在我看來,由於單線程模型,無法從另一個請求切換一個請求。 But the title of the example code says that everything runs in parallel except your code .但是示例代碼的標題說除了您的代碼之外所有內容都是並行運行的

(PS I'm not sure if I misunderstand the code or not since I have never used Node.)How Node switch A to B during the waiting? (PS 我不確定我是否誤解了代碼,因爲我從未使用過 Node。)Node 在等待期間如何將 A 切換到 B? And can you explain the single threaded non blocking IO model of Node in a simple way?並且可以簡單的解釋一下Node的單線程非阻塞IO模型嗎? I would appreciate it if you could help me.如果你能幫助我,我將不勝感激。 :) :)


解決方案:

參考一: https://stackoom.com/question/104tN
參考二: How the single threaded non blocking IO model works in Node.js
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章