libcopp 2.3.1
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
sample_readme_3.cpp
Go to the documentation of this file.
1#include <inttypes.h>
2#include <stdint.h>
3#include <cstdio>
4#include <cstring>
5#include <ctime>
6#include <iostream>
7
8// include context header file
9#include <libcotask/task.h>
11
12// create a task manager
13typedef cotask::task<> my_task_t;
14typedef my_task_t::ptr_t task_ptr_type;
15typedef cotask::task_manager<my_task_t> mgr_t;
16mgr_t::ptr_t task_mgr = mgr_t::create();
17
18// If you task manager to manage timeout, it's important to call tick interval
19
20void tick() {
21 // the first parameter is second, and the second is nanosecond
22 task_mgr->tick(time(nullptr), 0);
23}
24
25int main() {
26 // create two coroutine task
27 task_ptr_type co_task = my_task_t::create([]() {
28 std::cout << "task " << cotask::this_task::get<my_task_t>()->get_id() << " started" << std::endl;
29 cotask::this_task::get_task()->yield();
30 std::cout << "task " << cotask::this_task::get<my_task_t>()->get_id() << " resumed" << std::endl;
31 return 0;
32 });
33 task_ptr_type co_another_task = my_task_t::create([]() {
34 std::cout << "task " << cotask::this_task::get<my_task_t>()->get_id() << " started" << std::endl;
35 cotask::this_task::get_task()->yield();
36 std::cout << "task " << cotask::this_task::get<my_task_t>()->get_id() << " resumed" << std::endl;
37 return 0;
38 });
39
40 int res = task_mgr->add_task(co_task, 5, 0); // add task and setup 5s for timeout
41 if (res < 0) {
42 std::cerr << "some error: " << res << std::endl;
43 return res;
44 }
45
46 res = task_mgr->add_task(co_another_task); // add task without timeout
47 if (res < 0) {
48 std::cerr << "some error: " << res << std::endl;
49 return res;
50 }
51
52 res = task_mgr->start(co_task->get_id());
53 if (res < 0) {
54 std::cerr << "start task " << co_task->get_id() << " failed, error code: " << res << std::endl;
55 }
56
57 res = task_mgr->start(co_another_task->get_id());
58 if (res < 0) {
59 std::cerr << "start task " << co_another_task->get_id() << " failed, error code: " << res << std::endl;
60 }
61
62 res = task_mgr->resume(co_task->get_id());
63 if (res < 0) {
64 std::cerr << "resume task " << co_task->get_id() << " failed, error code: " << res << std::endl;
65 }
66
67 res = task_mgr->kill(co_another_task->get_id());
68 if (res < 0) {
69 std::cerr << "kill task " << co_another_task->get_id() << " failed, error code: " << res << std::endl;
70 } else {
71 std::cout << "kill task " << co_another_task->get_id() << " finished." << std::endl;
72 }
73
74 return 0;
75}
cotask::task my_task_t
cotask::task_manager< my_task_t > mgr_t
my_task_t::ptr_t task_ptr_type
void tick()
mgr_t::ptr_t task_mgr
int main()