Skip to content

Commit 5faa619

Browse files
committed
Add async spinlock
1 parent cc9e396 commit 5faa619

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

JavaScript/7-spin-lock.js

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
'use strict';
2+
3+
const threads = require('worker_threads');
4+
const { Worker, isMainThread } = threads;
5+
6+
const LOCKED = 0;
7+
const UNLOCKED = 1;
8+
9+
class Mutex {
10+
constructor(shared, offset = 0, initial = false) {
11+
this.lock = new Int32Array(shared, offset, 1);
12+
if (initial) Atomics.store(this.lock, 0, UNLOCKED);
13+
this.owner = false;
14+
if (!Mutex.collection) {
15+
Mutex.collection = new Set();
16+
}
17+
Mutex.collection.add(this);
18+
}
19+
20+
enter() {
21+
return new Promise(resolve => {
22+
const tryEnter = () => {
23+
let prev = Atomics.exchange(this.lock, 0, LOCKED);
24+
if (prev === UNLOCKED) {
25+
this.owner = true;
26+
resolve();
27+
} else {
28+
setTimeout(tryEnter, 0);
29+
}
30+
};
31+
tryEnter();
32+
});
33+
}
34+
35+
leave() {
36+
if (!this.owner) return false;
37+
Atomics.store(this.lock, 0, UNLOCKED);
38+
Atomics.notify(this.lock, 0, 1);
39+
this.owner = false;
40+
return true;
41+
}
42+
}
43+
44+
// Usage
45+
46+
if (isMainThread) {
47+
const buffer = new SharedArrayBuffer(4);
48+
const mutex = new Mutex(buffer, 0, true);
49+
console.dir({ mutex });
50+
new Worker(__filename, { workerData: buffer });
51+
new Worker(__filename, { workerData: buffer });
52+
} else {
53+
const { threadId, workerData } = threads;
54+
const mutex = new Mutex(workerData);
55+
56+
setInterval(() => {
57+
console.log(`Interval ${threadId}`);
58+
}, 500);
59+
60+
const f = async () => {
61+
await mutex.enter();
62+
console.log(`Enter ${threadId}`);
63+
setTimeout(() => {
64+
mutex.leave();
65+
console.log(`Leave ${threadId}`);
66+
f();
67+
}, 5000);
68+
};
69+
f();
70+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy