cluster.workers
存储活动工作进程对象的哈希,以 id
字段为键。
使循环遍历所有工作进程变得容易。
它仅在主进程中可用。
在工作进程断开连接并退出后,工作进程会从 cluster.workers
中删除。
这两个事件之间的顺序无法预先确定。
但是,可以保证从 cluster.workers
列表中的删除发生在最后一个 'disconnect'
或 'exit'
事件触发之前。
// 遍历所有工作进程
function eachWorker(callback) {
for (const id in cluster.workers) {
callback(cluster.workers[id]);
}
}
eachWorker((worker) => {
worker.send('big announcement to all workers');
});
使用工作进程的唯一 id 是定位工作进程的最简单方法。
socket.on('data', (id) => {
const worker = cluster.workers[id];
});
A hash that stores the active worker objects, keyed by id
field. Makes it
easy to loop through all the workers. It is only available in the master
process.
A worker is removed from cluster.workers
after the worker has disconnected
and exited. The order between these two events cannot be determined in
advance. However, it is guaranteed that the removal from the cluster.workers
list happens before last 'disconnect'
or 'exit'
event is emitted.
// Go through all workers
function eachWorker(callback) {
for (const id in cluster.workers) {
callback(cluster.workers[id]);
}
}
eachWorker((worker) => {
worker.send('big announcement to all workers');
});
Using the worker's unique id is the easiest way to locate the worker.
socket.on('data', (id) => {
const worker = cluster.workers[id];
});