GeezerVison is showing github.com — Fix BinarySemaphore: inverse 0 and 1 status · HowProgrammingWorks/Semaphore@548ab3c
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: JavaScript/2-binary.js +12-6Lines changed: 12 additions & 6 deletions | Original file line number | Diff line number | Diff line change |
|---|
|
3 | 3 | const threads = require('worker_threads'); |
4 | 4 | const { Worker, isMainThread } = threads; |
5 | 5 |
|
| 6 | +const LOCKED = 0; |
| 7 | +const UNLOCKED = 1; |
| 8 | + |
6 | 9 | class BinarySemaphore { |
7 | | - constructor(shared, offset = 0) { |
| 10 | + constructor(shared, offset = 0, init = false) { |
8 | 11 | this.lock = new Int8Array(shared, offset, 1); |
| 12 | + if (init) this.lock[0] = UNLOCKED; |
9 | 13 | } |
10 | 14 |
|
11 | 15 | enter() { |
12 | | - while (this.lock[0] !== 0); |
13 | | - this.lock[0] = 1; |
| 16 | + while (this.lock[0] !== UNLOCKED); |
| 17 | + this.lock[0] = LOCKED; |
14 | 18 | } |
15 | 19 |
|
16 | 20 | leave() { |
17 | | - if (this.lock[0] === 0) return; |
18 | | - this.lock[0] = 0; |
| 21 | + if (this.lock[0] === UNLOCKED) { |
| 22 | + throw new Error('Cannot leave unlocked BinarySemaphore'); |
| 23 | + } |
| 24 | + this.lock[0] = UNLOCKED; |
19 | 25 | } |
20 | 26 | } |
21 | 27 |
|
22 | 28 | // Usage |
23 | 29 |
|
24 | 30 | if (isMainThread) { |
25 | 31 | const buffer = new SharedArrayBuffer(11); |
26 | | - const semaphore = new BinarySemaphore(buffer); |
| 32 | + const semaphore = new BinarySemaphore(buffer, 0, true); |
27 | 33 | console.dir({ semaphore }); |
28 | 34 | new Worker(__filename, { workerData: buffer }); |
29 | 35 | new Worker(__filename, { workerData: buffer }); |
|