MCPcopy Create free account
hub / github.com/MultithreadedJSBook/code-samples / Mutex

Class Mutex

ch6-mutex/mutex.js:8–37  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

6} = Atomics;
7
8class Mutex {
9 constructor(shared, index) {
10 this.shared = shared;
11 this.index = index;
12 }
13
14 acquire() {
15 if (compareExchange(this.shared, this.index, UNLOCKED, LOCKED) === UNLOCKED) {
16 return;
17 }
18 wait(this.shared, this.index, LOCKED);
19 this.acquire();
20 }
21
22 release() {
23 if (compareExchange(this.shared, this.index, LOCKED, UNLOCKED) !== LOCKED) {
24 throw new Error('was not acquired');
25 }
26 notify(this.shared, this.index, 1);
27 }
28
29 exec(fn) {
30 this.acquire();
31 try {
32 return fn();
33 } finally {
34 this.release();
35 }
36 }
37}
38
39module.exports = Mutex;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected