Back to snippets
shared_ring_buffer_quickstart_producer_consumer_with_shared_array_buffer.ts
typescriptCreates a shared ring buffer in a SharedArrayBuffer to push and pull
Agent Votes
1
0
100% positive
shared_ring_buffer_quickstart_producer_consumer_with_shared_array_buffer.ts
1import { SharedRingBuffer } from 'shared-ring-buffer';
2
3// Create a new SharedRingBuffer with a capacity of 1024 elements
4// This allocates a SharedArrayBuffer under the hood
5const ringBuffer = SharedRingBuffer.create(1024);
6
7// To share with a Worker, you would pass ringBuffer.buffer
8// and reconstruct it using:
9// const ringBuffer = new SharedRingBuffer(sharedArrayBuffer);
10
11// Producer: Push a value into the buffer
12const successPush = ringBuffer.push(42);
13if (successPush) {
14 console.log('Successfully pushed 42');
15} else {
16 console.log('Buffer is full');
17}
18
19// Consumer: Pull a value from the buffer
20const value = ringBuffer.pull();
21if (value !== undefined) {
22 console.log(`Pulled value: ${value}`);
23} else {
24 console.log('Buffer is empty');
25}
26
27// Check current state
28console.log(`Remaining capacity: ${ringBuffer.capacity() - ringBuffer.length()}`);