084_async.zig 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //
  2. // Six Facts:
  3. //
  4. // 1. The memory space allocated to your program for the
  5. // invocation of a function and all of its data is called a
  6. // "stack frame".
  7. //
  8. // 2. The 'return' keyword "pops" the current function
  9. // invocation's frame off of the stack (it is no longer needed)
  10. // and returns control to the place where the function was
  11. // called.
  12. //
  13. // fn foo() void {
  14. // return; // Pop the frame and return control
  15. // }
  16. //
  17. // 3. Like 'return', the 'suspend' keyword returns control to the
  18. // place where the function was called BUT the function
  19. // invocation's frame remains so that it can regain control again
  20. // at a later time. Functions which do this are "async"
  21. // functions.
  22. //
  23. // fn fooThatSuspends() void {
  24. // suspend; // return control, but leave the frame alone
  25. // }
  26. //
  27. // 4. To call any function in async context and get a reference
  28. // to its frame for later use, use the 'async' keyword:
  29. //
  30. // var foo_frame = async fooThatSuspends();
  31. //
  32. // 5. If you call an async function without the 'async' keyword,
  33. // the function FROM WHICH you called the async function itself
  34. // becomes async! In this example, the bar() function is now
  35. // async because it calls fooThatSuspends(), which is async.
  36. //
  37. // fn bar() void {
  38. // fooThatSuspends();
  39. // }
  40. //
  41. // 6. The main() function cannot be async!
  42. //
  43. // Given facts 3 and 4, how do we fix this program (broken by facts
  44. // 5 and 6)?
  45. //
  46. const print = @import("std").debug.print;
  47. pub fn main() void {
  48. foo();
  49. }
  50. fn foo() void {
  51. print("foo() A\n", .{});
  52. suspend;
  53. print("foo() B\n", .{});
  54. }