forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwork_pool.zig
65 lines (53 loc) · 2.01 KB
/
work_pool.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const ThreadPool = bun.ThreadPool;
const std = @import("std");
const bun = @import("root").bun;
pub const Batch = ThreadPool.Batch;
pub const Task = ThreadPool.Task;
pub fn NewWorkPool(comptime max_threads: ?usize) type {
return struct {
var pool: ThreadPool = undefined;
var loaded: bool = false;
fn create() *ThreadPool {
@setCold(true);
pool = ThreadPool.init(.{
.max_threads = max_threads orelse bun.getThreadCount(),
.stack_size = ThreadPool.default_thread_stack_size,
});
return &pool;
}
/// Initialization of WorkPool is not thread-safe, as it is
/// assumed a single main thread sets everything up. Calling
/// this afterwards is thread-safe.
pub inline fn get() *ThreadPool {
if (loaded) return &pool;
loaded = true;
return create();
}
pub fn scheduleBatch(batch: ThreadPool.Batch) void {
get().schedule(batch);
}
pub fn schedule(task: *ThreadPool.Task) void {
get().schedule(ThreadPool.Batch.from(task));
}
pub fn go(allocator: std.mem.Allocator, comptime Context: type, context: Context, comptime function: fn (Context) void) !void {
const TaskType = struct {
task: Task,
context: Context,
allocator: std.mem.Allocator,
pub fn callback(task: *Task) void {
var this_task: *@This() = @fieldParentPtr("task", task);
function(this_task.context);
this_task.allocator.destroy(this_task);
}
};
var task_ = try allocator.create(TaskType);
task_.* = .{
.task = .{ .callback = TaskType.callback },
.context = context,
.allocator = allocator,
};
schedule(&task_.task);
}
};
}
pub const WorkPool = NewWorkPool(null);