-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path8-async.js
More file actions
94 lines (82 loc) · 2.06 KB
/
8-async.js
File metadata and controls
94 lines (82 loc) · 2.06 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'use strict';
const threads = require('node:worker_threads');
const { Worker, isMainThread } = threads;
const LOCKED = 0;
const UNLOCKED = 1;
class Mutex {
constructor(messagePort, shared, offset = 0, initial = false) {
this.port = messagePort;
this.lock = new Int32Array(shared, offset, 1);
if (initial) Atomics.store(this.lock, 0, UNLOCKED);
this.owner = false;
this.trying = false;
this.resolve = null;
if (messagePort) {
messagePort.on('message', (kind) => {
if (kind === 'leave' && this.trying) this.tryEnter();
});
}
}
enter() {
return new Promise((resolve) => {
this.resolve = resolve;
this.trying = true;
this.tryEnter();
});
}
tryEnter() {
if (!this.resolve) return;
const prev = Atomics.exchange(this.lock, 0, LOCKED);
if (prev === UNLOCKED) {
this.owner = true;
this.trying = false;
this.resolve();
this.resolve = null;
}
}
leave() {
if (!this.owner) return;
Atomics.store(this.lock, 0, UNLOCKED);
this.port.postMessage('leave');
this.owner = false;
}
}
class Thread {
constructor(data) {
const worker = new Worker(__filename, { workerData: data });
this.worker = worker;
Thread.workers.add(worker);
worker.on('message', (kind) => {
for (const next of Thread.workers) {
if (next !== worker) {
next.postMessage(kind);
}
}
});
}
}
Thread.workers = new Set();
// Usage
if (isMainThread) {
const buffer = new SharedArrayBuffer(4);
const mutex = new Mutex(null, buffer, 0, true);
console.dir({ mutex });
new Thread(buffer);
new Thread(buffer);
} else {
const { threadId, workerData, parentPort } = threads;
const mutex = new Mutex(parentPort, workerData);
setInterval(() => {
console.log(`Interval ${threadId}`);
}, 500);
const loop = async () => {
await mutex.enter();
console.log(`Enter ${threadId}`);
setTimeout(() => {
mutex.leave();
console.log(`Leave ${threadId}`);
setTimeout(loop, 0);
}, 5000);
};
loop();
}