summaryrefslogtreecommitdiff
path: root/exercises/089_async5.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/089_async5.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/089_async5.zig')
-rw-r--r--exercises/089_async5.zig61
1 files changed, 61 insertions, 0 deletions
diff --git a/exercises/089_async5.zig b/exercises/089_async5.zig
new file mode 100644
index 0000000..4fb8d76
--- /dev/null
+++ b/exercises/089_async5.zig
@@ -0,0 +1,61 @@
+//
+// One of the most important features of the new Io system is
+// structured cancellation!
+//
+// Every Future has a .cancel() method that:
+// 1. Requests the task to stop (via error.Canceled at the
+// next "cancellation point")
+// 2. Waits for the task to actually finish
+// 3. Returns whatever result the task produced
+//
+// A "cancellation point" is any Io function that can return
+// error.Canceled - most commonly io.sleep():
+//
+// fn myTask(io: std.Io) u32 {
+// io.sleep(...) catch |err| switch (err) {
+// error.Canceled => return 0, // handle gracefully
+// };
+// return 42;
+// }
+//
+// This is fundamentally different from killing a thread -
+// the task gets a chance to clean up and return a value!
+//
+// Fix this program: the slow task would take 10 seconds,
+// but we cancel it after 1 second. The task should detect
+// the cancellation and return early.
+//
+const std = @import("std");
+const print = std.debug.print;
+
+pub fn main(init: std.process.Init) !void {
+ const io = init.io;
+
+ var future = io.async(slowTask, .{io});
+
+ // Wait 1 second, then cancel instead of waiting the full 10.
+ io.sleep(std.Io.Duration.fromSeconds(1), .awake) catch {};
+
+ print("Canceling slow task...\n", .{});
+
+ // We don't want to wait 10 seconds!
+ // Which Future method requests cancellation AND returns the result?
+ const result = ???;
+
+ print("Task returned: {}\n", .{result});
+}
+
+fn slowTask(io: std.Io) u32 {
+ print("Starting long computation...\n", .{});
+
+ // Try to sleep for 10 seconds - but we might get canceled!
+ io.sleep(std.Io.Duration.fromSeconds(10), .awake) catch |err| switch (err) {
+ error.Canceled => {
+ print("Task was canceled, cleaning up.\n", .{});
+ return 0;
+ },
+ };
+
+ print("Task completed normally.\n", .{});
+ return 42;
+}