Created
April 14, 2025 13:24
-
-
Save mreinstein/04d58f4bffabb334c041396bbf8a7ce0 to your computer and use it in GitHub Desktop.
simple ringbuf example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { RingBuffer } from "ringbuf.js"; | |
import { Worker } from "worker_threads"; | |
// https://github.com/padenot/ringbuf.js/blob/main/js/ringbuf.js | |
// https://github.com/padenot/ringbuf.js/blob/main/tests/test.mjs | |
async function main () { | |
const arraySize = Math.round(Math.random() * 48000); | |
const pushPopSize = Math.round(Math.random() * arraySize); | |
const sab = RingBuffer.getStorageForCapacity(arraySize, Uint8Array); | |
const rb = new RingBuffer(sab, Uint8Array); | |
const toPop = new Uint8Array(pushPopSize); | |
const worker = new Worker("./worker.js"); | |
worker.postMessage({ | |
name: "seq-constant", | |
sharedArrayBuffer: sab, | |
params: [pushPopSize], | |
}); | |
function boss () { | |
console.log('main. available to read:', rb.available_read()); | |
rb.pop(toPop); | |
for (let i=0; i < 4; i++) | |
console.log('data[', i, '] =', toPop[i]) | |
setTimeout(boss, 1000); | |
} | |
boss(); | |
} | |
main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ringbuf from "ringbuf.js"; | |
import { parentPort } from "worker_threads"; | |
parentPort.postMessage("ok"); | |
parentPort.on("message", (data) => { | |
const sab = data.sharedArrayBuffer; | |
const packetSize = data.params[0]; | |
const arraySize = sab.byteLength / Uint8Array.BYTES_PER_ELEMENT; | |
const rb = new ringbuf.RingBuffer(sab, Uint8Array); | |
const toPush = new Uint8Array(packetSize); | |
/* | |
const generator = new mod.SequenceGenerator(); | |
// Go around the ring buffer about 1000 times for each test case | |
//let step = Math.round((arraySize * 1000) / packetSize); | |
function onestep() { | |
while (rb.available_write() >= toPush.length) { | |
generator.fill(toPush); | |
step--; | |
rb.push(toPush); | |
} | |
if (step > 0) { | |
setTimeout(onestep); | |
} else { | |
parentPort.postMessage("done"); | |
} | |
} | |
onestep(); | |
*/ | |
let offset = 0; | |
function onestep () { | |
for (let i=0; i < 16; i++) | |
toPush[i] = offset + i; | |
rb.push(toPush, 4); | |
offset++ | |
setTimeout(onestep, 2000); | |
} | |
onestep(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment