线程池
线程池解决了两个不同的问题:
- 在执行大量异步任务时,由于减少了每个任务的调用开销,它们通常提供更好的性能,并且
- 它们提供了一种限制和管理在执行任务集合时消耗的资源(包括线程)的方法。
在此示例中,我们将 10 个任务放入线程池,并使用 WaitGroup 等待它们完成。
const std = @import("std");
const print = std.debug.print;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer if (gpa.deinit() != .ok) @panic("leak");
const allocator = gpa.allocator();
var pool: std.Thread.Pool = undefined;
try pool.init(.{
.allocator = allocator,
.n_jobs = 4,
});
defer pool.deinit();
var wg: std.Thread.WaitGroup = .{};
for (0..10) |i| {
pool.spawnWg(&wg, struct {
fn run(id: usize) void {
print("I'm from {d}\n", .{id});
}
}.run, .{i});
}
wg.wait();
print("All threads exit.\n", .{});
}