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 — Fix BinarySemaphore: inverse 0 and 1 status · HowProgrammingWorks/Semaphore@548ab3c

File tree

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

‎JavaScript/2-binary.js‎

Copy file name to clipboardExpand all lines: JavaScript/2-binary.js
+12-6Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,27 +3,33 @@
33
const threads = require('worker_threads');
44
const { Worker, isMainThread } = threads;
55

6+
const LOCKED = 0;
7+
const UNLOCKED = 1;
8+
69
class BinarySemaphore {
7-
constructor(shared, offset = 0) {
10+
constructor(shared, offset = 0, init = false) {
811
this.lock = new Int8Array(shared, offset, 1);
12+
if (init) this.lock[0] = UNLOCKED;
913
}
1014

1115
enter() {
12-
while (this.lock[0] !== 0);
13-
this.lock[0] = 1;
16+
while (this.lock[0] !== UNLOCKED);
17+
this.lock[0] = LOCKED;
1418
}
1519

1620
leave() {
17-
if (this.lock[0] === 0) return;
18-
this.lock[0] = 0;
21+
if (this.lock[0] === UNLOCKED) {
22+
throw new Error('Cannot leave unlocked BinarySemaphore');
23+
}
24+
this.lock[0] = UNLOCKED;
1925
}
2026
}
2127

2228
// Usage
2329

2430
if (isMainThread) {
2531
const buffer = new SharedArrayBuffer(11);
26-
const semaphore = new BinarySemaphore(buffer);
32+
const semaphore = new BinarySemaphore(buffer, 0, true);
2733
console.dir({ semaphore });
2834
new Worker(__filename, { workerData: buffer });
2935
new Worker(__filename, { workerData: buffer });

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.