mirror of
https://codeberg.org/andyscott/ziglings.git
synced 2024-12-22 14:03:10 -05:00
add ex090 async 7
This commit is contained in:
parent
37ca10ab36
commit
34af14ca7b
3 changed files with 51 additions and 0 deletions
|
@ -438,6 +438,10 @@ const exercises = [_]Exercise{
|
||||||
.main_file = "089_async6.zig",
|
.main_file = "089_async6.zig",
|
||||||
.output = ".com: Example Title, .org: Example Title.",
|
.output = ".com: Example Title, .org: Example Title.",
|
||||||
},
|
},
|
||||||
|
.{
|
||||||
|
.main_file = "090_async7.zig",
|
||||||
|
.output = "beef? BEEF!",
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Check the zig version to make sure it can compile the examples properly.
|
/// Check the zig version to make sure it can compile the examples properly.
|
||||||
|
|
43
exercises/090_async7.zig
Normal file
43
exercises/090_async7.zig
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
//
|
||||||
|
// Remember how a function with 'suspend' is async and calling an
|
||||||
|
// async function without the 'async' keyword makes the CALLING
|
||||||
|
// function async?
|
||||||
|
//
|
||||||
|
// fn fooThatMightSuspend(maybe: bool) void {
|
||||||
|
// if (maybe) suspend {}
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// fn bar() void {
|
||||||
|
// fooThatMightSuspend(true); // Now bar() is async!
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// But if you KNOW the function won't suspend, you can make a
|
||||||
|
// promise to the compiler with the 'nosuspend' keyword:
|
||||||
|
//
|
||||||
|
// fn bar() void {
|
||||||
|
// nosuspend fooThatMightSuspend(false);
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// If the function does suspend and YOUR PROMISE TO THE COMPILER
|
||||||
|
// IS BROKEN, the program will panic at runtime, which is
|
||||||
|
// probably better than you deserve, you oathbreaker! >:-(
|
||||||
|
//
|
||||||
|
const print = @import("std").debug.print;
|
||||||
|
|
||||||
|
pub fn main() void {
|
||||||
|
|
||||||
|
// The main() function can not be async. But we know
|
||||||
|
// getBeef() will not suspend with this particular
|
||||||
|
// invocation. Please make this okay:
|
||||||
|
var my_beef = getBeef(0);
|
||||||
|
|
||||||
|
print("beef? {X}!\n", .{my_beef});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn getBeef(input: u32) u32 {
|
||||||
|
if (input > 0xDEAD) {
|
||||||
|
suspend {}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0xBEEF;
|
||||||
|
}
|
4
patches/patches/090_async7.patch
Normal file
4
patches/patches/090_async7.patch
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
32c32
|
||||||
|
< var my_beef = getBeef(0);
|
||||||
|
---
|
||||||
|
> var my_beef = nosuspend getBeef(0);
|
Loading…
Reference in a new issue