Skip to content

Instantly share code, notes, and snippets.

@pavelsavara
Created February 14, 2025 15:57
Show Gist options
  • Save pavelsavara/41b0f8c2c276532d50d8ce38fd43e81f to your computer and use it in GitHub Desktop.
Save pavelsavara/41b0f8c2c276532d50d8ce38fd43e81f to your computer and use it in GitHub Desktop.

Thread A, producer

const memory = new SharedArrayBuffer(16);

// produce 100 items and wake consumer after each 
for (let i = 0;i<100;i++){
    // wait for consumer to say it's ready
    Atomics.wait(memory, 0);

    // produce
    // ...
    // enqueue in some data structure

    // notify consumer
    Atomics.store(memory, 1)
    Atomics.notify(memory, 1, 1)
}

Thread B, consumer

while (true){

    // tell producer I'm ready
    Atomics.notify(memory, 1, 1)

    // short spin wait (is optimal when you have multiple cores)
    let cnt=0;
    while (Atomics.load(memory, 1) == 0 || cnt < 100) {
        // spinning for a while
        cnt++;
    }
    if(cnt == 100){
        // kernel wait, is more expensive
        Atomics.wait(memory, 1);
    }

    // process the item
    // ...

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment