libcopp 2.3.1
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
sample_readme_9.cpp
Go to the documentation of this file.
1/*
2 * sample_readme_9.cpp
3 *
4 * Created on: 2020-05-20
5 * Author: owent
6 *
7 * Released under the MIT license
8 */
9
10#include <iostream>
11
12// include manager header file
14#include <libcotask/task.h>
15
16#if defined(LIBCOPP_MACRO_ENABLE_STD_COROUTINE) && LIBCOPP_MACRO_ENABLE_STD_COROUTINE
17
18typedef cotask::task<> my_task_t;
19
20static copp::callable_future<int> call_for_await_cotask(my_task_t::ptr_t t) {
21 if (t) {
22 auto ret = co_await t;
23 co_return ret;
24 }
25
26 co_return 0;
27}
28
29static int cotask_action_callback(void*) {
30 int ret = 234;
31 void* ptr = nullptr;
32 cotask::this_task::get_task()->yield(&ptr);
33 if (ptr != nullptr) {
34 ret = *reinterpret_cast<int*>(ptr);
35 }
36 return ret;
37}
38
39int main() {
40 my_task_t::ptr_t co_task = my_task_t::create(cotask_action_callback);
41
42 auto t = call_for_await_cotask(co_task);
43 co_task->start();
44
45 int res = 345;
46 co_task->resume(reinterpret_cast<void*>(&res));
47
48 std::cout << "co_await a cotask::task and get result: " << t.get_internal_promise().data() << std::endl;
49 return 0;
50}
51#else
52int main() {
53 puts("this sample require cotask enabled and compiler support c++20 coroutine");
54 return 0;
55}
56#endif
cotask::task my_task_t
int main()