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
// ...
}