LoginSignup
7
2

More than 5 years have passed since last update.

Node.js スレッドモデルとイベントループとは

Last updated at Posted at 2018-08-12

スレッドモデルとイベントループ

大量のリクエストをさばくための処理形式

スレッドモデル

Requestに対し、Threadを立ち上げて対応
大量に来ると、Request処理待ちが発生する

イベントループ(Node.js)

QueueでEventLoopを回す(メインのスレッド)
 →Requestをためる
I/O(バックグラウンドのスレッド)

メリット:
前の処理が終わるまで待つ必要がない
デメリット:
処理の終了順番が把握できない
ループをブロックしないプログラミング(NON-Blocking)が必要

ノンブロッキングな書き方とは

時間の掛かりそうな処理はコールバック関数で書く

test1.js
//non blocking
setTimeout(function() {
    console.log("hello");
}, 1000);
console.log("world");

結果:helloの処理(表示)を待たずにworldが表示される

test2.js
//blocking
var start = new Date.getDate()
while (new Date.getDate() < start + 1000);
console.log("world");

結果:helloの処理(表示)を待ってworldが表示される

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2