summaryrefslogtreecommitdiff
path: root/exercises/093_async9.zig
diff options
context:
space:
mode:
authorChris Boesch <chrboesch@noreply.codeberg.org>2026-04-03 19:32:53 +0200
committerChris Boesch <chrboesch@noreply.codeberg.org>2026-04-03 19:32:53 +0200
commit5307b2a338a92130bc498fb1dc7d21a9fd1b0db4 (patch)
tree51279ca4fbd7bd90294dd563640c12a8c25c79c6 /exercises/093_async9.zig
parent3056a2b5442f2f1ec58db3f3493109064ad2a2a5 (diff)
parentf6a6798c8b6b813bd2ceee81db276e05327a76e0 (diff)
Merge pull request 'revival of the async-io functions' (#383) from asyncIo into main
Reviewed-on: https://codeberg.org/ziglings/exercises/pulls/383
Diffstat (limited to 'exercises/093_async9.zig')
-rw-r--r--exercises/093_async9.zig57
1 files changed, 57 insertions, 0 deletions
diff --git a/exercises/093_async9.zig b/exercises/093_async9.zig
new file mode 100644
index 0000000..ad30dcf
--- /dev/null
+++ b/exercises/093_async9.zig
@@ -0,0 +1,57 @@
+//
+// We've been using io.async() to launch tasks. But there's a
+// stronger variant: io.concurrent().
+//
+// The difference:
+//
+// io.async():
+// * The function MAY run on another thread, or it may run
+// immediately on the current thread (synchronously).
+// * Never fails — if no thread is available, it just runs
+// the function right away.
+// * More portable, works with all Io backends.
+//
+// io.concurrent():
+// * GUARANTEES a separate unit of concurrency (a real thread
+// in the Threaded backend).
+// * Can fail with error.ConcurrencyUnavailable if resources
+// are exhausted or the backend doesn't support it.
+// * Use when you NEED true parallelism.
+//
+// Because concurrent() can fail, you must handle the error:
+//
+// var future = try io.concurrent(myFn, .{args});
+// const result = future.await(io);
+//
+// Notice the 'try' — that's the key difference in usage!
+//
+// Fix this program to launch the computation concurrently.
+//
+const std = @import("std");
+const print = std.debug.print;
+
+pub fn main(init: std.process.Init) !void {
+ const io = init.io;
+
+ // Launch with a guaranteed separate thread.
+ // Which Io method guarantees true concurrency?
+ // (Hint: unlike io.async, this one can fail!)
+ var future = try io.???(compute, .{io});
+
+ print("Main thread continues...\n", .{});
+
+ // Wait 100 millisecond so the output order is deterministic.
+ io.sleep(std.Io.Duration.fromMilliseconds(100), .awake) catch {};
+
+ print("Main thread done waiting.\n", .{});
+
+ const result = future.await(io);
+ print("Result: {}\n", .{result});
+}
+
+fn compute(io: std.Io) u32 {
+ print("Computing on a separate thread!\n", .{});
+ // Simulate some work.
+ io.sleep(std.Io.Duration.fromMilliseconds(200), .awake) catch return 0;
+ return 123;
+}