libcopp  2.2.0
sample_readme_5.cpp
Go to the documentation of this file.
1 /*
2  * sample_readme_5.cpp
3  *
4  * Created on: 2014-05-19
5  * Author: owent
6  *
7  * Released under the MIT license
8  */
9 
10 #include <assert.h>
11 #include <inttypes.h>
12 #include <stdint.h>
13 #include <cstdio>
14 #include <cstdlib>
15 #include <cstring>
16 #include <ctime>
17 #include <vector>
18 
20 
21 // include manager header file
22 #include <libcotask/task.h>
23 
24 #if defined(LIBCOTASK_MACRO_ENABLED)
25 
26 typedef cotask::task<> my_task_t;
27 
28 int main() {
29  int test_code = 128;
30 
31  // create a task using lambda expression
32  my_task_t::ptr_t first_task = my_task_t::create([&]() {
33  puts("|first task running and will be yield ...");
35  puts("|first task resumed ...");
36  printf("test code already reset => %d\n", ++test_code);
37  });
38 
39  // add many then task using lambda expression
40  first_task
41  ->then([=]() {
42  puts("|second task running...");
43  printf("test code should be inited 128 => %d\n", test_code);
44  })
45  ->then([&]() {
46  puts("|haha ... this is the third task.");
47  printf("test code is the same => %d\n", ++test_code);
48  return "return value will be ignored";
49  })
50  ->then(
51  [&](EXPLICIT_UNUSED_ATTR void *priv_data) {
52  puts("|it's boring");
53  printf("test code is %d\n", ++test_code);
54  assert(&test_code == priv_data);
55  return 0;
56  },
57  &test_code);
58 
59  test_code = 0;
60  // start a task
61  first_task->start();
62  first_task->resume();
63 
64  // these code below will failed.
65  first_task->then([]() {
66  puts("this will run immediately.");
67  return 0;
68  });
69 
70  my_task_t::ptr_t await_task = my_task_t::create([&]() {
71  puts("await_task for first_task.");
72  return 0;
73  });
74  await_task->await_task(first_task);
75 
76  printf("|task start twice will failed: %d\n", first_task->start());
77  printf("|test_code end with %d\n", test_code);
78  return 0;
79 }
80 #else
81 int main() {
82  puts("this sample require cotask enabled");
83  return 0;
84 }
85 #endif
virtual int yield(void **priv_data)=0
导入继承关系约束 Licensed under the MIT licenses.
#define EXPLICIT_UNUSED_ATTR
maybe_unused, 标记忽略unused警告 usage: EXPLICIT_UNUSED_ATTR int a; class EXPLICIT_UNUSED_ATTR a; EXPLICIT_...
LIBCOPP_COTASK_API impl::task_impl * get_task() LIBCOPP_MACRO_NOEXCEPT
get current running task
Definition: this_task.cpp:9
cotask::task my_task_t
int main()