Node.js Concurrency Deep Dive

Node.js 并发深入剖析

Node.js 並行処理の詳細

Understanding the Node.js Event Loop, `libuv`, Worker Threads, and Clustering to build high-performance, non-blocking applications.

了解 Node.js 事件循环、`libuv`、工作线程和集群,以构建高性能、非阻塞的应用程序。

Node.jsイベントループ、`libuv`、ワーカースレッド、およびクラスタリングを理解し、高性能なノンブロッキングアプリケーションを構築します。

The Event Loop & Libuv

事件循环与 Libuv

イベントループとLibuv

Node.js is single-threaded but scalable due to its event-driven architecture powered by libuv. The Event Loop allows Node.js to perform non-blocking I/O operations by offloading operations to the system kernel whenever possible.

Node.js 是单线程的,但由于其由 libuv 驱动的事件驱动架构,它具有可扩展性。事件循环允许 Node.js 通过尽可能将操作卸载到系统内核来执行非阻塞 I/O 操作。

Node.jsはシングルスレッドですが、libuvを利用したイベント駆動型アーキテクチャによりスケーラブルです。イベントループは、可能な限り操作をシステムカーネルにオフロードすることで、Node.jsがノンブロッキングI/O操作を実行できるようにします。

Event Loop Phases

事件循环阶段

イベントループのフェーズ

  1. Timers: Executes callbacks scheduled by `setTimeout()` and `setInterval()`. 定时器: 执行由 `setTimeout()` 和 `setInterval()` 调度的回调。 タイマー: `setTimeout()` および `setInterval()` によってスケジュールされたコールバックを実行します。
  2. Pending Callbacks: Executes I/O callbacks deferred to the next loop iteration. 待处理回调: 执行推迟到下一次循环迭代的 I/O 回调。 保留中のコールバック: 次のループ反復に延期されたI/Oコールバックを実行します。
  3. Poll: Retrieves new I/O events; executes I/O related callbacks. 轮询: 检索新的 I/O 事件;执行与 I/O 相关的回调。 ポール: 新しいI/Oイベントを取得し、I/O関連のコールバックを実行します。
  4. Check: Executes callbacks triggered by `setImmediate()`. 检查: 执行由 `setImmediate()` 触发的回调。 チェック: `setImmediate()` によってトリガーされたコールバックを実行します。
  5. Close Callbacks: Executes close events, e.g., `socket.on('close', ...)`. 关闭回调: 执行关闭事件,例如 `socket.on('close', ...)`。 クローズコールバック: 終了イベント(例:`socket.on('close', ...)`)を実行します。

Worker Threads

工作线程

ワーカースレッド

The `worker_threads` module enables the use of threads that execute JavaScript in parallel. Worker threads are useful for performing CPU-intensive JavaScript operations, as they do not block the Event Loop.

`worker_threads` 模块允许使用并行执行 JavaScript 的线程。工作线程对于执行 CPU 密集型 JavaScript 操作非常有用,因为它们不会阻塞事件循环。

`worker_threads` モジュールは、JavaScriptを並列実行するスレッドの使用を可能にします。ワーカースレッドは、イベントループをブロックしないため、CPU集約型のJavaScript操作を実行するのに役立ちます。

// main.js
const { Worker } = require('worker_threads');

function runService(workerData) {
  return new Promise((resolve, reject) => {
    const worker = new Worker('./worker.js', { workerData });
    worker.on('message', resolve);
    worker.on('error', reject);
    worker.on('exit', (code) => {
      if (code !== 0)
        reject(new Error(`Worker stopped with exit code ${code}`));
    });
  });
}

Clustering

集群

クラスタリング

The `cluster` module allows you to create child processes (workers) that run simultaneously and share the same server port. This takes advantage of multi-core systems, balancing the load across available cores.

`cluster` 模块允许您创建同时运行并共享同一服务器端口的子进程(工作进程)。这利用了多核系统,在可用核心之间平衡负载。

`cluster` モジュールを使用すると、同時に実行され、同じサーバーポートを共有する子プロセス(ワーカー)を作成できます。これにより、マルチコアシステムを活用し、使用可能なコア間で負荷分散を行うことができます。

References

参考资料

参考文献

  1. Node.js Docs. (n.d.). The Node.js Event Loop, Timers, and process.nextTick(). Retrieved from nodejs.org Node.js 文档. (n.d.). Node.js 事件循环、定时器和 process.nextTick()。 取自 nodejs.org Node.js ドキュメント. (n.d.). Node.js イベントループ、タイマー、および process.nextTick()。 取得元 nodejs.org
  2. Node.js Docs. (n.d.). Worker Threads. Retrieved from nodejs.org/api/worker_threads Node.js 文档. (n.d.). 工作线程。 取自 nodejs.org/api/worker_threads Node.js ドキュメント. (n.d.). ワーカースレッド。 取得元 nodejs.org/api/worker_threads
  3. Node.js Docs. (n.d.). Cluster. Retrieved from nodejs.org/api/cluster Node.js 文档. (n.d.). 集群。 取自 nodejs.org/api/cluster Node.js ドキュメント. (n.d.). クラスター。 取得元 nodejs.org/api/cluster