libcopp  2.2.0
sample_readme_6.cpp
Go to the documentation of this file.
1 // Copyright 2023 owent
2 // Created by owent on 2022-05-27
3 
4 #include <iostream>
5 
6 // include manager header file
8 
9 #if defined(LIBCOPP_MACRO_ENABLE_STD_COROUTINE) && LIBCOPP_MACRO_ENABLE_STD_COROUTINE
10 
11 static copp::callable_future<int> coroutine_callable_with_int_result() {
12  // ... any code
13  co_return 123;
14 }
15 
16 static copp::callable_future<void> coroutine_callable_with_void_result() {
17  // ... any code
18  co_return;
19 }
20 
21 static copp::callable_future<void> coroutine_simulator_task() {
22  // suspend and wait custom waker
23  (void)co_await LIBCOPP_MACRO_STD_COROUTINE_NAMESPACE suspend_always();
24  // ... any code
25  // We can get current status by co_yield yield_status()
26  auto current_status = co_yield copp::callable_future<int>::yield_status();
27  // The return value will be ignored when the future is already set by custom waker
28  std::cout << "Current coroutine callable status: " << static_cast<uint32_t>(current_status) << std::endl;
29 
30  co_await coroutine_callable_with_void_result();
31 
32  int result = co_await coroutine_callable_with_int_result();
33  std::cout << "Coroutine int callable result: " << result << std::endl;
34  co_return;
35 }
36 
37 int main() {
38  auto rpc_result = coroutine_simulator_task();
39 
40  // We should not explict call start and get_internal_handle().resume() in a real usage
41  // It's only allowed to start and resume by co_wait the callable_future object
42  rpc_result.get_internal_handle().resume(); // resume co_await LIBCOPP_MACRO_STD_COROUTINE_NAMESPACE suspend_always();
43 
44  std::cout << "Current coroutine callable status: " << static_cast<uint32_t>(rpc_result.get_status()) << std::endl;
45  return 0;
46 }
47 #else
48 int main() {
49  puts("this sample require cotask enabled and compiler support c++20 coroutine");
50  return 0;
51 }
52 #endif
#define LIBCOPP_MACRO_STD_COROUTINE_NAMESPACE
Definition: coroutine.h:41
int main()