my ziglings
0

Configure Feed

Select the types of activity you want to include in your feed.

improvements for async-io

Chris Boesch (Apr 5, 2026, 4:13 PM +0200) 5e474ea5 2acf1927

+17 -25
+11 -12
exercises/087_async3.zig
··· 5 5 // them all. The Io backend may run them concurrently: 6 6 // 7 7 // var f1 = io.async(taskA, .{}); 8 + // defer _ = f1.cancel(io); 8 9 // var f2 = io.async(taskB, .{}); 9 - // 10 - // // Both tasks may be running now! 10 + // defer _ = f2.cancel(io); 11 11 // const a = f1.await(io); 12 12 // const b = f2.await(io); 13 13 // 14 - // There's also io.concurrent() which provides a STRONGER guarantee: 15 - // it ensures the function gets its own unit of concurrency (e.g. a 16 - // real OS thread). But it can fail with error.ConcurrencyUnavailable 17 - // if resources are exhausted. 18 - // 19 - // io.async() is more portable: if no thread is available, it simply 20 - // runs the function synchronously. This makes it the right default 21 - // for most code. 14 + // Notice the defer pattern: each async call is immediately 15 + // followed by a defer cancel. This ensures cleanup even if 16 + // we return early or hit an error before reaching await. 17 + // Since await/cancel are idempotent, the defer is harmless 18 + // if we've already awaited. 22 19 // 23 20 // Fix this program to launch both tasks and collect their results. 24 21 // ··· 29 26 const io = init.io; 30 27 31 28 // Launch both tasks asynchronously. 32 - var future_a = io.async(slowAdd, .{ 10, 20 }); 29 + var future_a = io.async(slowAdd, .{ 1, 2 }); 30 + defer _ = future_a.cancel(io); 33 31 var future_b = ???(slowMul, .{ 6, 7 }); 32 + defer _ = future_b.cancel(io); 34 33 35 34 // Await both results. 36 35 const sum = future_a.await(io); 37 - const product = future_b.???(io); 36 + const product = future_b.await(io); 38 37 39 38 print("{} + {} = {}\n", .{ 1, 2, sum }); 40 39 print("{} * {} = {}\n", .{ 6, 7, product });
+6 -13
patches/patches/087_async3.patch
··· 1 - --- exercises/087_async3.zig 2026-04-01 22:51:05.540094851 +0200 2 - +++ answers/087_async3.zig 2026-04-01 22:50:44.579669189 +0200 3 - @@ -29,12 +29,12 @@ 4 - const io = init.io; 5 - 1 + --- exercises/087_async3.zig 2026-04-05 16:12:48.317265515 +0200 2 + +++ answers/087_async3.zig 2026-04-05 16:12:52.269343030 +0200 3 + @@ -28,7 +28,7 @@ 6 4 // Launch both tasks asynchronously. 7 - - var future_a = io.async(slowAdd, .{ 10, 20 }); 5 + var future_a = io.async(slowAdd, .{ 1, 2 }); 6 + defer _ = future_a.cancel(io); 8 7 - var future_b = ???(slowMul, .{ 6, 7 }); 9 - + var future_a = io.async(slowAdd, .{ 1, 2 }); 10 8 + var future_b = io.async(slowMul, .{ 6, 7 }); 9 + defer _ = future_b.cancel(io); 11 10 12 11 // Await both results. 13 - const sum = future_a.await(io); 14 - - const product = future_b.???(io); 15 - + const product = future_b.await(io); 16 - 17 - print("{} + {} = {}\n", .{ 1, 2, sum }); 18 - print("{} * {} = {}\n", .{ 6, 7, product });