dahlia-concurrency
Version:
High-level concurrency primitives and patterns for Node.js using worker_threads (queues, semaphore, mutex, worker pool, scheduler, and more)
36 lines (32 loc) • 812 B
JavaScript
class CountingSemaphore {
constructor(sharedBuffer, threads = 1) {
this.counter = new Int32Array(sharedBuffer);
if (threads <= 0) {
throw new Error("Threads must be a positive integer");
}
if (typeof threads === "number") {
Atomics.store(this.counter, 0, threads);
}
}
acquire() {
while (true) {
let current = Atomics.load(this.counter, 0);
if (current > 0) {
const previous = current - 1;
if (
Atomics.compareExchange(this.counter, 0, current, previous) ===
current
) {
return;
}
} else {
Atomics.wait(this.counter, 0, 0);
}
}
}
release() {
Atomics.add(this.counter, 0, 1);
Atomics.notify(this.counter, 0, 1);
}
}
module.exports = { CountingSemaphore };