090_async7.zig 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. //
  2. // Remember how a function with 'suspend' is async and calling an
  3. // async function without the 'async' keyword makes the CALLING
  4. // function async?
  5. //
  6. // fn fooThatMightSuspend(maybe: bool) void {
  7. // if (maybe) suspend {}
  8. // }
  9. //
  10. // fn bar() void {
  11. // fooThatMightSuspend(true); // Now bar() is async!
  12. // }
  13. //
  14. // But if you KNOW the function won't suspend, you can make a
  15. // promise to the compiler with the 'nosuspend' keyword:
  16. //
  17. // fn bar() void {
  18. // nosuspend fooThatMightSuspend(false);
  19. // }
  20. //
  21. // If the function does suspend and YOUR PROMISE TO THE COMPILER
  22. // IS BROKEN, the program will panic at runtime, which is
  23. // probably better than you deserve, you oathbreaker! >:-(
  24. //
  25. const print = @import("std").debug.print;
  26. pub fn main() void {
  27. // The main() function can not be async. But we know
  28. // getBeef() will not suspend with this particular
  29. // invocation. Please make this okay:
  30. var my_beef = getBeef(0);
  31. print("beef? {X}!\n", .{my_beef});
  32. }
  33. fn getBeef(input: u32) u32 {
  34. if (input > 0xDEAD) {
  35. suspend {}
  36. }
  37. return 0xBEEF;
  38. }