A thread-safe communication bridge for Zig applications. This project implements a Bounded Multi-Producer Multi-Consumer (MPMC) Channel using a Ring Buffer architecture, specifically optimized for real-time applications.
- Zero Allocations: Uses a fixed-capacity
comptimearray. No heap allocations during the game loop. - Non-Blocking UI: Uses
try_receiveto poll for worker updates without freezing. - Efficient Workers: Background threads use
receiveto sleep on a semaphore, consuming 0% CPU until work arrives. - Safety First: Uses
std.Thread.Mutexandstd.Thread.Semaphoreto guarantee memory visibility and prevent race conditions.
| Method | Type | Best For | Behavior |
|---|---|---|---|
send |
Blocking | Workers | Waits if the channel is full. |
try_send |
Non-blocking | UI Thread | Returns false if the channel is full. |
receive |
Blocking | Workers | Sleeps until data is available. |
try_receive |
Non-blocking | UI Thread | Returns null if the channel is empty. |
const context = struct {
chan: *Channel(i32, 1),
fn worker(chan: *Channel(i32, 1)) void {
std.Thread.sleep(10 * std.time.ns_per_ms);
chan.send(42);
}
};
var chan = Channel(i32, 1){};
const thread = try std.Thread.spawn(.{}, context.worker, .{&chan});
defer thread.join();
// This will block until the worker sends
const val = chan.recieve();
try std.testing.expectEqual(@as(i32, 42), val);