Skip to content

Instantly share code, notes, and snippets.

@Lightnet
Created June 25, 2026 03:00
Show Gist options
  • Select an option

  • Save Lightnet/e6a67462588e9dd89e22df909b3c82d7 to your computer and use it in GitHub Desktop.

Select an option

Save Lightnet/e6a67462588e9dd89e22df909b3c82d7 to your computer and use it in GitHub Desktop.
sample raylib thread
//
// do not use gpu in thread
// zig 0.16.0
// https://github.com/raylib-zig/raylib-zig.git
const std = @import("std");
const rl = @import("raylib");
const SharedData = struct {
mutex: std.Io.Mutex = .init,
progress: i32 = 0,
result_ready: bool = false,
};
const WorkerArgs = struct {
data: *SharedData,
io: std.Io,
};
fn backgroundWorker(args: WorkerArgs) void {
const io = args.io;
const data = args.data;
for (0..10) |i| {
io.sleep(std.Io.Duration{ .nanoseconds = 500 * 1_000_000 }, .awake) catch return;
data.mutex.lock(io) catch return;
data.progress = @intCast((i + 1) * 10);
data.mutex.unlock(io); // FIXED: Added io parameter
}
data.mutex.lock(io) catch return;
data.result_ready = true;
data.mutex.unlock(io); // FIXED: Added io parameter
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
const screenWidth = 800;
const screenHeight = 450;
rl.initWindow(screenWidth, screenHeight, "Threaded Raylib-Zig Example");
defer rl.closeWindow();
rl.setTargetFPS(60);
var shared_data = SharedData{};
const thread = try std.Thread.spawn(.{}, backgroundWorker, .{WorkerArgs{
.data = &shared_data,
.io = io,
}});
defer thread.detach();
while (!rl.windowShouldClose()) {
try shared_data.mutex.lock(io);
const current_progress = shared_data.progress;
const is_done = shared_data.result_ready;
shared_data.mutex.unlock(io); // FIXED: Added io parameter
rl.beginDrawing();
rl.clearBackground(.ray_white);
if (!is_done) {
rl.drawText("Calculating in background thread...", 40, 40, 20, .dark_gray);
rl.drawRectangle(40, 100, current_progress * 3, 30, .blue);
} else {
rl.drawText("Task Complete!", 40, 40, 20, .green);
}
rl.endDrawing();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment