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 — Implement async symaphore with queue · HowProgrammingWorks/Semaphore@988b024

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • JavaScript
    • 4-async.js
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎JavaScript/4-async.js‎

Copy file name to clipboard
+59Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
'use strict';
2+
3+
const fs = require('fs');
4+
const threads = require('worker_threads');
5+
const { Worker, isMainThread } = threads;
6+
7+
class CountingSemaphore {
8+
constructor(shared, offset = 0, initial) {
9+
this.counter = new Uint32Array(shared, offset, 1);
10+
if (typeof initial === 'number') {
11+
this.counter[0] = initial;
12+
}
13+
this.queue = [];
14+
}
15+
16+
enter(callback) {
17+
if (this.counter[0] > 0) {
18+
this.counter[0]--;
19+
callback();
20+
} else {
21+
this.queue.push(callback);
22+
}
23+
}
24+
25+
leave() {
26+
this.counter[0]++;
27+
if (this.queue.length > 0) {
28+
const callback = this.queue.shift();
29+
this.counter[0]--;
30+
callback();
31+
}
32+
}
33+
}
34+
35+
// Usage
36+
37+
if (isMainThread) {
38+
const buffer = new SharedArrayBuffer(4);
39+
const semaphore = new CountingSemaphore(buffer, 0, 10);
40+
console.dir({ semaphore: semaphore.counter[0] });
41+
for (let i = 0; i < 20; i++) {
42+
new Worker(__filename, { workerData: buffer });
43+
}
44+
} else {
45+
const { threadId, workerData } = threads;
46+
const semaphore = new CountingSemaphore(workerData);
47+
console.dir({ threadId, semaphore: semaphore.counter[0] });
48+
const REPEAT_COUNT = 1000000;
49+
const file = `file-${threadId}.dat`;
50+
51+
semaphore.enter(() => {
52+
const data = `Data from ${threadId}`.repeat(REPEAT_COUNT);
53+
fs.writeFile(file, data, () => {
54+
fs.unlink(file, () => {
55+
semaphore.leave();
56+
});
57+
});
58+
});
59+
}

0 commit comments

Comments
0 (0)
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.