Skip to content

Jkeyuk/jthread

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

jthread

Overview

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.

🚀 Why Use This?

  • Zero Allocations: Uses a fixed-capacity comptime array. No heap allocations during the game loop.
  • Non-Blocking UI: Uses try_receive to poll for worker updates without freezing.
  • Efficient Workers: Background threads use receive to sleep on a semaphore, consuming 0% CPU until work arrives.
  • Safety First: Uses std.Thread.Mutex and std.Thread.Semaphore to guarantee memory visibility and prevent race conditions.

🛠 Features

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.

📦 Usage Example

    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);

About

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.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages