深度理解nodejs[2]-事件迴圈
阿新 • • 發佈:2018-11-20
程序與執行緒
我們在電腦中會執行多個程式,每一個程式中都會有多個執行緒。
例如我們執行比特幣客戶端的時候,我們某一個執行緒要處理網路、某一個執行緒要處理挖礦、某一個執行緒要處理使用者輸入…
執行緒的排程使用了作業系統級別的排程器來明確了哪一個執行緒應該被執行。執行緒也有優先順序之分,例如監聽滑鼠滑動的優先順序就會很高,因為其不能等待太長的時間。
為了在給定的時間內更快更多的處理執行緒:
1、我們可以通過增加CPU的核心數量或者是
2、排程器當監測到執行緒中執行中斷,如讀取檔案網路時,及時切換到其他的執行緒中執行。
事件迴圈
nodejs是單執行緒的事件迴圈機制
虛擬碼演示事件迴圈:
1 |
const peningTimers =[]; |
nodejs的單執行緒與多執行緒
nodejs的單執行緒,是對於其處理事件迴圈來講的,有了事件觸發,就會執行相應函式。沒有事件觸發,就會等待。從這個意義上來說,nodejs是單執行緒的。
但是在處理具體的任務,函式的時候。nodejs確是多執行緒的。
nodejs的單執行緒與多執行緒證明
1 |
const crypto = require('crypto'); |
測試pbkdf2速度:1: 868
1 |
const crypto = require('crypto'); |
測試pbkdf2速度:
1 |
1: 891 |
說明了pbkdf2函式是多執行緒來執行的。libuv中預設有4個執行緒,pbkdf2函式正是藉助libuv實現了多執行緒。
測試libuv中預設有4個執行緒
1 |
const crypto = require('crypto'); |
1 |
4: 919 |
注意,明顯第5個執行緒時間增加了一倍,因為預設libuv中預設有4個執行緒,第5個執行緒陷入了等待。
修改libuv中預設預設執行緒
1 |
process.env.UV_THREADPOOL_SIZE = 5; |
測試速度:
1 |
1: 956 |
http庫
1 |
const https = require('https'); |
測試速度:
1 |
48 |
https網路訪問,呼叫了作業系統資源,libuv只是起到了代理的作用,所以不收到libuv預設4個執行緒的限制。
總結
版權宣告: 本部落格所有文章除特別宣告外,均採用 CC BY 4.0 CN協議 許可協議。轉載請註明出處!