I'm not familiar with Node.js, but when I was writing asynchronous code, in which the threads were supposed to wait for each other to reach a common barrier point, I used the following class:
class CyclicBarrier {
waitingParties = [];
limit;
constructor(limit) {
this.limit = limit;
}
release() {
while (this.waitingParties.length) {
this.waitingParties
.pop()
.call();
}
}
register() {
return new Promise((resolve, reject) => {
this.waitingParties.push(resolve);
if (this.waitingParties.length >= this.limit) {
this.release();
}
});
}
}
The limit
parameter defines how often register()
has to be called, before all pending Promises are resolved at once.
const barrier = new CyclicBarrier(4);
Later code then simply uses await
:
async function f(barrier) {
...
// Pauses execution until enough threads are registered.
await barrier.register();
...
}
The class was influenced by the CyclicBarrier
Java class.