Skip to content

Instantly share code, notes, and snippets.

@empijei
Created March 26, 2019 22:07
Show Gist options
  • Save empijei/40100a2e6197a4041c0988151454403c to your computer and use it in GitHub Desktop.
Save empijei/40100a2e6197a4041c0988151454403c to your computer and use it in GitHub Desktop.
waitgroup.js
class WaitGroup {
constructor(initial, opt_sab) {
this._sab = opt_sab || new SharedArrayBuffer(4);
this._wg = new Int32Array(this._sab);
this.add(initial);
}
static connect(wg) { return new WaitGroup(0, wg._sab) }
add(n) {
let current = n + Atomics.add(this._wg, 0, n);
if (current < 0) {
throw new Error('WaitGroup is in inconsistent state: negative count.');
}
if (current > 0){ return }
Atomics.notify(this._wg, 0);
}
done() { this.add(-1) }
wait() {
for (;;) {
let count = Atomics.load(this._wg, 0);
if (count == 0){ return }
if (Atomics.wait(this._wg, 0, count) == 'ok') { return }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment