Thread Pool in Zig
This Zig program demonstrates the use of a thread pool to execute concurrent tasks.
const std = @import("std");
pub fn main() !void {
const allocator = std.heap.page_allocator;
var pool: std.Thread.Pool = undefined;
try pool.init(std.Thread.Pool.Options{ .allocator = allocator, .n_jobs = 5 });
defer pool.deinit();
try pool.spawn(work, .{3});
try pool.spawn(work, .{5});
try pool.spawn(work, .{7});
}
fn work(inc: u32) void {
std.debug.print("Start Inc = {d}\n", .{inc});
var total: u32 = 0;
var i: u32 = 0;
while (i < 100000) : (i += 1) {
total += inc;
}
std.debug.print("Total = {d}, Inc = {d}\n", .{ total, inc });
}
The code begins by importing the standard library (std) and defining the main() function, which can return an error (!void). Inside main(), a page allocator is obtained from the heap for memory management. A thread pool named pool is then initialized with options specifying the allocator and a maximum of 5 concurrent jobs (threads). The defer statement ensures the pool is deinitialized when main() exits, preventing resource leaks. The program spawns three tasks using the spawn() method on the pool, each calling the work function with different unsigned 32-bit integer arguments: 3, 5, and 7. These tasks run concurrently, managed by the thread pool.
The work function takes a single parameter inc of type u32 and performs a simple computation. It first prints a starting message with the value of inc using std.debug.print, formatted to display the integer. It initializes a total variable to 0 and a loop counter i to 0. A while loop runs 100,000 iterations, incrementing i by 1 each time and adding inc to total in every iteration. After the loop, it prints the final total (which should be inc multiplied by 100,000) along with the original inc value. Since the tasks are spawned concurrently, the output order of the print statements may vary depending on thread scheduling, illustrating non-deterministic behavior in multithreaded execution.
When run, it would output starting and completion messages for each increment value, with totals of 300,000, 500,000, and 700,000 respectively, though interleaved in an unpredictable sequence due to threading.
Save this as threadPool.zig and run with zig run threadPool.zig:
$ zig version
0.15.2
$ zig run threadPool.zig
Start Inc = 3
Start Inc = 7
Start Inc = 5
Total = 300000, Inc = 3
Total = 700000, Inc = 7
Total = 500000, Inc = 5
Happy coding in Zig!