Skip to content

Commit 0ef5621

Browse files
committed
Fix safe implementation of CouningSemaphore
1 parent d507478 commit 0ef5621

1 file changed

Lines changed: 8 additions & 3 deletions

File tree

JavaScript/6-counting-safe.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,14 @@ class CountingSemaphore {
1313
}
1414

1515
enter() {
16-
Atomics.wait(this.counter, 0, 0);
17-
const prev = Atomics.sub(this.counter, 0, 1);
18-
if (prev === 0) this.leave();
16+
while (true) {
17+
Atomics.wait(this.counter, 0, 0);
18+
const n = Atomics.load(this.counter, 0, 1);
19+
if (n > 0) {
20+
const prev = Atomics.compareExchange(this.counter, 0, n, n - 1);
21+
if (prev === n) return;
22+
}
23+
}
1924
}
2025

2126
leave() {

0 commit comments

Comments
 (0)