Skip to content

Instantly share code, notes, and snippets.

@mreinstein
Created April 14, 2025 13:24
Show Gist options
  • Select an option

  • Save mreinstein/04d58f4bffabb334c041396bbf8a7ce0 to your computer and use it in GitHub Desktop.

Select an option

Save mreinstein/04d58f4bffabb334c041396bbf8a7ce0 to your computer and use it in GitHub Desktop.

Revisions

  1. mreinstein created this gist Apr 14, 2025.
    39 changes: 39 additions & 0 deletions main.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    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()
    48 changes: 48 additions & 0 deletions worker.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    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();
    });