libcopp 2.3.1
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
sample_readme_12.cpp
Go to the documentation of this file.
1/*
2 * sample_readme_12.cpp
3 *
4 * Created on: 2025-03-05
5 * Author: owent
6 *
7 * Released under the MIT license
8 */
9
10#include <iostream>
11
12// include task header file
14#include <libcotask/task.h>
15
16typedef cotask::task<> my_task_t;
17
18int main() {
19 // Returns <receiver, sender>
20 auto channel = copp::make_stackful_channel<int>();
21 // Create a task and use channel to receive data
22 {
23 my_task_t::ptr_t task = my_task_t::create([&channel]() {
24 std::cout << "task " << cotask::this_task::get<my_task_t>()->get_id() << " started" << std::endl;
25 auto receiver = channel.first;
26 int value = cotask::this_task::get<my_task_t>()->await_value(receiver);
27 std::cout << "task " << cotask::this_task::get<my_task_t>()->get_id() << " resumed, got value: " << value
28 << std::endl;
29 return 0;
30 });
31
32 task->start();
33 channel.second.set_value(42);
34 }
35
36 // Use channel and custom transform function to receive error
37 channel.first.reset_value();
38 {
39 my_task_t::ptr_t task = my_task_t::create([&channel]() {
40 std::cout << "task " << cotask::this_task::get<my_task_t>()->get_id() << " started" << std::endl;
41 auto receiver = channel.first;
42 int value = cotask::this_task::get<my_task_t>()->await_value(receiver, [](copp::copp_error_code) { return -5; });
43 std::cout << "task " << cotask::this_task::get<my_task_t>()->get_id() << " resumed, got value: " << value
44 << std::endl;
45 return 0;
46 });
47
48 task->start();
49 task->kill();
50 }
51
52 return 0;
53}
Definition task.h:38
int kill(enum EN_TASK_STATUS status, void *priv_data) override
Definition task.h:661
int start(void *priv_data, EN_TASK_STATUS expected_status=EN_TS_CREATED) override
Definition task.h:523
cotask::task my_task_t
int main()