-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path2-binary.js
More file actions
49 lines (42 loc) · 1.2 KB
/
2-binary.js
File metadata and controls
49 lines (42 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
'use strict';
const threads = require('node:worker_threads');
const { Worker, isMainThread } = threads;
const LOCKED = 0;
const UNLOCKED = 1;
class BinarySemaphore {
constructor(shared, offset = 0, init = false) {
this.lock = new Int8Array(shared, offset, 1);
if (init) this.lock[0] = UNLOCKED;
}
enter() {
while (this.lock[0] !== UNLOCKED);
this.lock[0] = LOCKED;
}
leave() {
if (this.lock[0] === UNLOCKED) {
throw new Error('Cannot leave unlocked BinarySemaphore');
}
this.lock[0] = UNLOCKED;
}
}
// Usage
if (isMainThread) {
const buffer = new SharedArrayBuffer(11);
const semaphore = new BinarySemaphore(buffer, 0, true);
console.dir({ semaphore });
new Worker(__filename, { workerData: buffer });
new Worker(__filename, { workerData: buffer });
} else {
const { threadId, workerData } = threads;
const semaphore = new BinarySemaphore(workerData);
const array = new Int8Array(workerData, 1);
const value = threadId === 1 ? 1 : -1;
setInterval(() => {
semaphore.enter();
for (let i = 0; i < 10; i++) {
array[i] += value;
}
console.dir([ threadId, array ]);
semaphore.leave();
}, 100); // change to 10 to see race condition
}