task_of_void.pass.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // -*- C++ -*-
  2. //===----------------------------------------------------------------------===//
  3. //
  4. // The LLVM Compiler Infrastructure
  5. //
  6. // This file is dual licensed under the MIT and the University of Illinois Open
  7. // Source Licenses. See LICENSE.TXT for details.
  8. //
  9. //===----------------------------------------------------------------------===//
  10. // UNSUPPORTED: c++98, c++03, c++11, c++14
  11. #include <experimental/task>
  12. #include "../manual_reset_event.hpp"
  13. #include "../sync_wait.hpp"
  14. #include <optional>
  15. #include <thread>
  16. namespace coro = std::experimental::coroutines_v1;
  17. static bool has_f_executed = false;
  18. static coro::task<void> f()
  19. {
  20. has_f_executed = true;
  21. co_return;
  22. }
  23. static void test_coroutine_executes_lazily()
  24. {
  25. coro::task<void> t = f();
  26. assert(!has_f_executed);
  27. coro::sync_wait(t);
  28. assert(has_f_executed);
  29. }
  30. static std::optional<int> last_value_passed_to_g;
  31. static coro::task<void> g(int a)
  32. {
  33. last_value_passed_to_g = a;
  34. co_return;
  35. }
  36. void test_coroutine_accepts_arguments()
  37. {
  38. auto t = g(123);
  39. assert(!last_value_passed_to_g);
  40. coro::sync_wait(t);
  41. assert(last_value_passed_to_g);
  42. assert(*last_value_passed_to_g == 123);
  43. }
  44. int shared_value = 0;
  45. int read_value = 0;
  46. coro::task<void> consume_async(manual_reset_event& event)
  47. {
  48. co_await event;
  49. read_value = shared_value;
  50. }
  51. void produce(manual_reset_event& event)
  52. {
  53. shared_value = 101;
  54. event.set();
  55. }
  56. void test_async_completion()
  57. {
  58. manual_reset_event e;
  59. std::thread t1{ [&e]
  60. {
  61. sync_wait(consume_async(e));
  62. }};
  63. assert(read_value == 0);
  64. std::thread t2{ [&e] { produce(e); }};
  65. t1.join();
  66. assert(read_value == 101);
  67. t2.join();
  68. }
  69. int main()
  70. {
  71. test_coroutine_executes_lazily();
  72. test_coroutine_accepts_arguments();
  73. test_async_completion();
  74. return 0;
  75. }