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