MCPcopy Create free account
hub / github.com/MultithreadedJSBook/code-samples / SharedRingBuffer

Class SharedRingBuffer

ch6-ring-buffer/ring-buffer.js:89–107  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

87const Mutex = require('../ch6-mutex/mutex.js');
88
89class SharedRingBuffer {
90 constructor(shared/*: number | SharedArrayBuffer*/) {
91 this.shared = typeof shared === 'number' ?
92 new SharedArrayBuffer(shared + 16) : shared;
93 this.ringBuffer = new RingBuffer(
94 new Uint32Array(this.shared, 4, 3),
95 new Uint8Array(this.shared, 16)
96 );
97 this.lock = new Mutex(new Int32Array(this.shared, 0, 1));
98 }
99
100 write(data) {
101 return this.lock.exec(() => this.ringBuffer.write(data));
102 }
103
104 read(bytes) {
105 return this.lock.exec(() => this.ringBuffer.read(bytes));
106 }
107}
108
109const { isMainThread, Worker, workerData } = require('worker_threads');
110const fs = require('fs');

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected