| 1 |
"use strict"; |
| 2 |
Object.defineProperty(exports, "__esModule", { value: true }); |
| 3 |
exports.AtomicCounter = void 0; |
| 4 |
/** |
| 5 |
* A counter that can be atomically incremented and decremented, and which |
| 6 |
* callers can synchronously listen for it becoming non-zero. |
| 7 |
* |
| 8 |
* This can be "open" or "closed"; once it's closed, {@link wait} will no longer |
| 9 |
* emit useful events. |
| 10 |
*/ |
| 11 |
class AtomicCounter { |
| 12 |
/** |
| 13 |
* The underlying BigInt64Array. |
| 14 |
* |
| 15 |
* The first BigInt64 represents the current value of the counter. The second |
| 16 |
* BigInt64 is used to track the closed state. |
| 17 |
*/ |
| 18 |
buffer; |
| 19 |
constructor(buffer) { |
| 20 |
if (buffer.byteLength !== 16) { |
| 21 |
throw new Error('SharedArrayBuffer must have a byteLength of 16.'); |
| 22 |
} |
| 23 |
this.buffer = new BigInt64Array(buffer); |
| 24 |
} |
| 25 |
/** Atomically decrement the current value by one. */ |
| 26 |
decrement() { |
| 27 |
Atomics.sub(this.buffer, 0, 1n); |
| 28 |
} |
| 29 |
/** Atomically increment the current value by one. */ |
| 30 |
increment() { |
| 31 |
if (Atomics.add(this.buffer, 0, 1n) === 0n) { |
| 32 |
Atomics.notify(this.buffer, 0, 1); |
| 33 |
} |
| 34 |
} |
| 35 |
/** |
| 36 |
* Closes the counter. |
| 37 |
* |
| 38 |
* This will cause any outstanding calls to {@link wait} on any thread to |
| 39 |
* return `true` immediately. |
| 40 |
*/ |
| 41 |
close() { |
| 42 |
// The current value is no longer relevant once closed, therefore set it to |
| 43 |
// non-zero to prevent a potential deadlock when `Atomics.notify` is called |
| 44 |
// immediately before `Atomics.wait`. |
| 45 |
if (Atomics.compareExchange(this.buffer, 1, 0n, 1n) === 0n && |
| 46 |
Atomics.compareExchange(this.buffer, 0, 0n, 1n) === 0n) { |
| 47 |
Atomics.notify(this.buffer, 0); |
| 48 |
} |
| 49 |
} |
| 50 |
/** |
| 51 |
* Waits until the current value is not zero or the counter is closed. |
| 52 |
* |
| 53 |
* Returns `true` when the counter is non-zero *or* when it's closed. Returns |
| 54 |
* `false` if the counter remains zero for `timeout` milliseconds. |
| 55 |
*/ |
| 56 |
wait(timeout) { |
| 57 |
while (Atomics.load(this.buffer, 0) === 0n && |
| 58 |
Atomics.load(this.buffer, 1) === 0n) { |
| 59 |
const result = Atomics.wait(this.buffer, 0, 0n, timeout); |
| 60 |
if (result !== 'ok') { |
| 61 |
return result !== 'timed-out'; |
| 62 |
} |
| 63 |
} |
| 64 |
return true; |
| 65 |
} |
| 66 |
} |
| 67 |
exports.AtomicCounter = AtomicCounter; |
| 68 |
//# sourceMappingURL=atomic_counter.js.map |