libcopp  1.1.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 
20 // include manager header file
21 #include <libcotask/task.h>
22 
23 #if defined(LIBCOTASK_MACRO_ENABLED) && defined(UTIL_CONFIG_COMPILER_CXX_LAMBDAS) && UTIL_CONFIG_COMPILER_CXX_LAMBDAS
24 
26 
27 int main(int argc, char *argv[]) {
28  int test_code = 128;
29 
30  // create a task using lambda expression
31  my_task_t::ptr_t first_task = my_task_t::create([&]() {
32  puts("|first task running and will be yield ...");
34  puts("|first task resumed ...");
35  printf("test code already reset => %d\n", ++test_code);
36  });
37 
38  // add many then task using lambda expression
39  first_task
40  ->then([=]() {
41  puts("|second task running...");
42  printf("test code should be inited 128 => %d\n", test_code);
43  })
44  ->then([&]() {
45  puts("|haha ... this is the third task.");
46  printf("test code is the same => %d\n", ++test_code);
47  return "return value will be ignored";
48  })
49  ->then(
50  [&](void *priv_data) {
51  puts("|it's boring");
52  printf("test code is %d\n", ++test_code);
53  assert(&test_code == priv_data);
54  return 0;
55  },
56  &test_code);
57 
58  test_code = 0;
59  // start a task
60  first_task->start();
61  first_task->resume();
62 
63  // these code below will failed.
64  first_task->then([]() {
65  puts("this will run immediately.");
66  return 0;
67  });
68 
69  my_task_t::ptr_t await_task = my_task_t::create([&]() {
70  puts("await for first_task.");
71  return 0;
72  });
73  await_task->await(first_task);
74 
75  printf("|task start twice will failed: %d\n", first_task->start());
76  printf("|test_code end with %d\n", test_code);
77  return 0;
78 }
79 #else
80 int main() {
81  puts("this sample require cotask enabled and compiler support c++11");
82  return 0;
83 }
84 #endif
cotask::task my_task_t
int main()
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:155
impl::task_impl * get_task() UTIL_CONFIG_NOEXCEPT
get current running task
Definition: this_task.cpp:15
virtual int yield(void **priv_data)=0