aboutsummaryrefslogtreecommitdiff
path: root/lib/std/Thread
diff options
context:
space:
mode:
authorAndrew Kelley <andrew@ziglang.org>2024-03-06 22:25:35 -0700
committerAndrew Kelley <andrew@ziglang.org>2024-03-10 17:51:07 -0700
commit3efdfe612ec7aaf252f6391b4d29bbf46118eced (patch)
treed4187a0f555e84ef23e6bbd4e8be89a9f83c1d94 /lib/std/Thread
parentffd53a459e1b665e5070987f68dd583171a12459 (diff)
downloadzig-3efdfe612ec7aaf252f6391b4d29bbf46118eced.tar.gz
zig-3efdfe612ec7aaf252f6391b4d29bbf46118eced.zip
std.Thread.WaitGroup: add spawnManaged
Provides a convenient way to spawn a new thread that bypasses a thread pool. Appropriate when the spawned thread delegates all of its work.
Diffstat (limited to 'lib/std/Thread')
-rw-r--r--lib/std/Thread/WaitGroup.zig22
1 files changed, 22 insertions, 0 deletions
diff --git a/lib/std/Thread/WaitGroup.zig b/lib/std/Thread/WaitGroup.zig
index a6a82a9492..d85188fa78 100644
--- a/lib/std/Thread/WaitGroup.zig
+++ b/lib/std/Thread/WaitGroup.zig
@@ -1,3 +1,4 @@
+const builtin = @import("builtin");
const std = @import("std");
const assert = std.debug.assert;
const WaitGroup = @This();
@@ -43,3 +44,24 @@ pub fn isDone(wg: *WaitGroup) bool {
return (state / one_pending) == 0;
}
+
+// Spawns a new thread for the task. This is appropriate when the callee
+// delegates all work.
+pub fn spawnManager(
+ wg: *WaitGroup,
+ comptime func: anytype,
+ args: anytype,
+) void {
+ if (builtin.single_threaded) {
+ @call(.auto, func, args);
+ return;
+ }
+ const Manager = struct {
+ fn run(wg_inner: *WaitGroup, args_inner: @TypeOf(args)) void {
+ defer wg_inner.finish();
+ @call(.auto, func, args_inner);
+ }
+ };
+ wg.start();
+ _ = std.Thread.spawn(.{}, Manager.run, .{ wg, args }) catch Manager.run(wg, args);
+}