Skip to content

zigar.thread.WorkQueue(ns).init(self, options)

Chung Leong edited this page Dec 3, 2025 · 12 revisions

Initialize the work queue, allocating necessary memory and spawning worker threads.

You can use promisify() to define a basic startup function instead. When you only need a single thread, you can rely on the queue auto-initializing itself.

Usage

const std = @import("std");

const zigar = @import("zigar");

var work_queue: zigar.thread.WorkQueue(worker) = .{};
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();

pub fn startup(num_threads: usize) !void {
    try work_queue.init(.{
        .allocator = allocator,
        .n_jobs = num_threads,
        .thread_start_params = .{ allocator, 1234, "Rats live on no evil star" },
        .thread_end_params = .{allocator},
    });
}

pub const shutdown = work_queue.promisify(.shutdown);
pub const print = work_queue.promisify(worker.print);

const worker = struct {
    threadlocal var text: []const u8 = undefined;

    pub fn onThreadStart(a: std.mem.Allocator, number: i32, string: []const u8) !void {
        text = try std.fmt.allocPrint(a, "number = {d}, string = {s}\n", .{ number, string });
    }

    pub fn onThreadEnd(a: std.mem.Allocator) void {
        a.free(text);
    }

    pub fn print() void {
        std.debug.print("{s}\n", .{text});
    }
};
import { print, startup, shutdown } from './work-queue-example-2.zig';

startup(4);
await print();
await shutdown();
number = 1234, string = Rats live on no evil star

Arguments:

  • self: @This()
  • options: Options

Return value:

error{ Deinitializing, OutOfMemory, LockedMemoryLimitExceeded, SystemResources, ThreadQuotaExceeded, Unexpected, UnableToUseThread }!void

Note:

If the work queue has already been initialized, nothing happens.


WorkQueue(ns) | Options

Clone this wiki locally