GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Semaphore/JavaScript/5-atomics.js at master · HowProgrammingWorks/Semaphore

Expand file tree

/

5-atomics.js

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
52 lines (45 loc) · 1.33 KB
/

5-atomics.js

Copy path

File metadata and controls

52 lines (45 loc) · 1.33 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
'use strict';
const fs = require('node:fs');
const threads = require('node:worker_threads');
const { Worker, isMainThread } = threads;
class CountingSemaphore {
constructor(shared, offset = 0, initial) {
this.counter = new Int32Array(shared, offset, 1);
if (typeof initial === 'number') {
Atomics.store(this.counter, 0, initial);
}
}
enter(callback) {
Atomics.wait(this.counter, 0, 0);
Atomics.sub(this.counter, 0, 1);
setTimeout(callback, 0);
}
leave() {
Atomics.add(this.counter, 0, 1);
Atomics.notify(this.counter, 0, 1);
}
}
// Usage
if (isMainThread) {
const buffer = new SharedArrayBuffer(4);
// Try to change 10 to 2 at next line to check solution
const semaphore = new CountingSemaphore(buffer, 0, 10);
console.dir({ semaphore: semaphore.counter[0] });
for (let i = 0; i < 20; i++) {
new Worker(__filename, { workerData: buffer });
}
} else {
const { threadId, workerData } = threads;
const semaphore = new CountingSemaphore(workerData);
console.dir({ threadId, semaphore: semaphore.counter[0] });
const REPEAT_COUNT = 1000000;
const file = `file-${threadId}.dat`;
semaphore.enter(() => {
const data = `Data from ${threadId}`.repeat(REPEAT_COUNT);
fs.writeFile(file, data, () => {
fs.unlink(file, () => {
semaphore.leave();
});
});
});
}
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.