Blocking I/O หยุด thread ที่เรียกไว้จนกว่าการทำงานจะเสร็จ; non-blocking I/O คืนค่าทันทีและปล่อยให้ thread ไปทำงานอื่นในระหว่างที่การทำงานเสร็จสิ้น Sync กับ async อธิบายแนวคิดเดียวกันในระดับ API
Blocking I/O หยุด thread ที่เรียกไว้จนกว่าการทำงานจะเสร็จ; non-blocking I/O คืนค่าทันทีและปล่อยให้ thread ไปทำงานอื่นในระหว่างที่การทำงานเสร็จสิ้น Sync กับ async อธิบายแนวคิดเดียวกันในระดับ API
read() จนกว่าข้อมูลจะมา ง่าย แต่ thread ว่างอยู่ตลอดเวลา — การรองรับ client ที่ช้า N ราย คุณต้องใช้ N threadBlocking: ──[ wait for disk ]── (thread stuck, does nothing)
Non-blocking: ──▶ returns now; event loop notified when ready
// Blocking: nothing else runs until the file is read
const data = fs.readFileSync('big.txt');
// Non-blocking: thread keeps going; callback fires later
fs.readFile('big.txt', (err, data) => { /* handle later */ });
// or async/await on top of non-blocking primitives
const data2 = await fs.promises.readFile('big.txt');
นี่คือแก่นของเซิร์ฟเวอร์ที่ขยายได้ Node.js และ nginx รองรับจำนวน connection มหาศาลด้วย thread ไม่กี่ตัวก็เพราะ I/O เป็นแบบ non-blocking — การรอไม่ผูก thread ไว้ ใช้การเรียกแบบ blocking เพื่อความง่ายในสคริปต์; ใช้ non-blocking สำหรับบริการเครือข่ายที่มี concurrency สูง และอย่าบล็อก event loop ด้วยงานที่ใช้ CPU หนัก
คลังคำถามสัมภาษณ์งาน IT พร้อมคำตอบโดยละเอียด — ตั้งแต่ระดับ Junior ถึง Senior
บริจาค