• Stars
    star
    222
  • Rank 179,123 (Top 4 %)
  • Language
    C++
  • Created about 2 years ago
  • Updated 25 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Coroutines for C++20 & asio

boost.cobalt

This library provides a set of easy to use coroutine primitives & utilities running on top of boost.asio. These will be of interest for applications that perform a lot of IO that want to not block unnecessarily, yet still want to have linear & readable code (i..e. avoid callbacks).

A minimum of Boost 1.82 is necessary as the ASIO in that version has needed support. C++ 20 is needed for C++ coroutines.

Below is a showcase of features, if you're new to coroutines or asynchronous programming, please see the primer.

The assumptions are:

  • io_context is the execution_context of choice.
  • If asio::io_context is the executor, no more than one kernel thread executes within it at a time.
  • Eager execution is the way to go.
  • A thread created with promise is only using promise stuff.

Entry points

// a single threaded main running on an io_context
cobalt::main co_main(int argc, char ** argv)
{
    // wrapper around asio::steady_timer
    asio::steady_timer tim{co_await cobalt::this_coro::executor};
    dt.expires_after(std::chrono::milliseconds(100));

    co_await tim.async_wait(cobalt::use_op);
    co_return 0;
}

That is, main runs on a single threaded io_context.

It also hooks up signals, so that things like Ctrl+C get forwarded as cancellations automatically

Alternatively, run can be used manually.

cobalt::task<int> main_func()
{
    asio::steady_timer tim{co_await cobalt::this_coro::executor};
    dt.expires_after(std::chrono::milliseconds(100));

    co_await tim.async_wait(cobalt::use_op);
    co_return 0;
}


int main(int argc, char ** argv)
{
    return run(main_func());
}

Promises

The core primitive for creating your own functions is cobalt::promise<T>. It is eager, i.e. it starts execution immediately, before you co_await.

cobalt::promise<void> test()
{
    printf("test-1\n");
    asio::steady_timer tim{co_await cobalt::this_coro::executor};
    dt.expires_after(std::chrono::milliseconds(100));
    co_await tim.async_wait(cobalt::use_op);
    printf("test-2\n");
}

cobalt::main co_main(int argc, char ** argv)
{
    printf("main-1\n");
    auto tt = test();
    printf("main-2\n");
    co_await tt;
    printf("main-3\n");
    return 0;
}

The output of the above will be:

main-1
test-1
main-2
test-2
main-3

Unlike ops, returned by .wait, the promise can be disregarded; disregarding the promise does not cancel it, but rather detaches is. This makes it easy to spin up multiple tasks to run in parallel. In order to avoid accidental detaching the promise type uses nodiscard unless one uses + to detach it:

cobalt::promise<void> my_task();

cobalt::main co_main()
{
    // warns & cancels the task
    my_task();
    // ok
    +my_task();
    co_return 0;
}

Task

A task is a lazy alternative to a promise, that can be spawned onto or co_awaited on another executor.

An cobalt::task can also be used with spawn to turn it into an asio operation.

Generator

A generator is a coroutine that produces a series of values instead of one, but otherwise similar to promise.

cobalt::generator<int> test()
{
  printf("test-1\n");
  co_yield 1;
  printf("test-2\n");
  co_yield 2;
  printf("test-3\n");
  co_return 3;
}

cobalt::main co_main(int argc, char ** argv)
{
    printf("main-1\n");
    auto tt = test();
    printf("main-2\n");
    i = co_await tt; // 1
    printf("main-3: %d\n", i);
    i = co_await tt; // 2
    printf("main-4: %d\n", i);
    i = co_await tt; // 3
    printf("main-5: %d\n", i);
    co_return 0;
}
main-1
test-1
main-2
main-3: 1
test-2
main-4: 2
test-3
main-5: 3

Channels

Channels are modeled on golang; they are different from boost.asio channels in that they don't go through the executor. Instead they directly context switch when possible.

cobalt::promise<void> test(cobalt::channel<int> & chan)
{
  printf("Reader 1: %d\n", co_await chan.read());
  printf("Reader 2: %d\n", co_await chan.read());
  printf("Reader 3: %d\n", co_await chan.read());
}

cobalt::main co_main(int argc, char ** argv)
{
  cobalt::channel<int> chan{0u /* buffer size */};
  
  auto p = test(chan);
  
  printf("Writer 1\n");
  co_await chan.write(10);
  printf("Writer 2\n");
  co_await chan.write(11);
  printf("Writer 3\n");
  co_await chan.write(12);
  printf("Writer 4\n");
  
  co_await p;
  co_return 0u;
}
Writer-1
Reader-1: 10
Writer-2
Reader-1: 11
Writer-3
Reader-1: 12
Writer-4

Ops

To make writing asio operations that have an early completion easier, cobalt has an op-helper:

template<typename Timer>
struct wait_op : cobalt::op<system::error_code> // enable_op is to use ADL
{
  Timer & tim;

  wait_op(Timer & tim) : tim(tim) {}
  
  // this gets used to determine if it needs to suspend for the op
  void ready(cobalt::handler<system::error_code> h)
  {
    if (tim.expiry() < Timer::clock_type::now())
      h(system::error_code(asio::error::operation_aborted));
  }
  
  // this gets used to initiate the op if ti needs to suspend
  void initiate(cobalt::completion_handler<system::error_code> complete)
  {
    tim.async_wait(std::move(complete));
  }
};

cobalt::main co_main(int argc, char ** argv)
{
  cobalt::steady_timer tim{co_await cobalt::this_coro::executor}; // already expired
  co_await wait_op(tim); // will not suspend, since its ready
}

race

race let's you await multiple awaitables at once.

cobalt::promise<void> delay(int ms)
{
    asio::steady_timer tim{co_await cobalt::this_coro::executor};
    dt.expires_after(std::chrono::milliseconds(ms));
    co_await tim.async_wait(cobalt::use_op);
}

cobalt::main co_main(int argc, char ** argv)
{
  auto res = co_await race(delay(100), delay(50));
  asert(res == 1); // delay(50) completes earlier, delay(100) is not cancelled  
  co_return 0u;
}

More Repositories

1

boost

Super-project for modularized Boost
HTML
6,236
star
2

beast

HTTP and WebSocket built on Boost.Asio in C++11
C++
4,355
star
3

hana

Your standard library for metaprogramming
C++
1,690
star
4

compute

A C++ GPU Computing Library for OpenCL
C++
1,487
star
5

pfr

std::tuple like methods for user defined types without any macro or boilerplate code
C++
1,221
star
6

asio

Boost.org asio module
C++
1,212
star
7

hof

Higher-order functions for c++
C++
504
star
8

geometry

Boost.Geometry - Generic Geometry Library | Requires C++14 since Boost 1.75
C++
457
star
9

fiber

userland threads
C++
457
star
10

json

A C++11 library for parsing and serializing JSON to and from a DOM container in memory.
C++
434
star
11

python

Boost.org python module
C++
432
star
12

spirit

Boost.org spirit module
C++
390
star
13

stacktrace

C++ library for storing and printing backtraces.
C++
374
star
14

histogram

Fast multi-dimensional generalized histogram with convenient interface for C++14
C++
315
star
15

math

Boost.org math module
C++
310
star
16

context

Assembly
299
star
17

graph

Boost.org graph module
C++
285
star
18

leaf

Lightweight Error Augmentation Framework
C++
275
star
19

mysql

MySQL C++ client based on Boost.Asio
C++
254
star
20

mp11

C++11 metaprogramming library
C++
239
star
21

build

B2 makes it easy to build C++ projects, everywhere.
C++
224
star
22

redis

An async redis client designed for performance and scalability
C++
223
star
23

safe_numerics

Replacements to standard numeric types which throw exceptions on errors
C++
208
star
24

thread

Boost.org thread module
C++
198
star
25

multiprecision

Boost.Multiprecision
C++
195
star
26

url

Boost.URL is a library for manipulating Uniform Resource Identifiers (URIs) and Locators (URLs).
C++
186
star
27

test

The reference C++ unit testing framework (TDD, xUnit, C++03/11/14/17)
C++
178
star
28

gil

Boost.GIL - Generic Image Library | Requires C++14 since Boost 1.80
C++
178
star
29

log

Boost Logging library
C++
173
star
30

nowide

Boost.Nowide - Standard library functions with UTF-8 API on Windows
C++
171
star
31

filesystem

Boost.org filesystem module
C++
158
star
32

core

Boost Core Utilities
C++
133
star
33

interprocess

Boost.org interprocess module
C++
132
star
34

callable_traits

modern C++ type traits and metafunctions for callable types
C++
129
star
35

coroutine2

Boost.Coroutine2
C++
127
star
36

lockfree

Boost.Lockfree
C++
120
star
37

serialization

Boost.org serialization module
C++
119
star
38

process

Boost Process
C++
117
star
39

wiki

Boost Wiki
115
star
40

algorithm

Boost.org algorithm module
C++
112
star
41

ublas

Boost.uBlas
C++
108
star
42

smart_ptr

Boost.org smart_ptr module
C++
108
star
43

yap

A C++14-and-later expression template library
C++
107
star
44

container

STL-like containers from Boost
C++
101
star
45

program_options

Boost.org program_options module
C++
92
star
46

preprocessor

Boost.org preprocessor module
C++
91
star
47

cmake

CMake support infrastructure Boost submodule
CMake
87
star
48

uuid

Boost.org uuid module
C++
84
star
49

regex

Boost.org regex module
C++
84
star
50

qvm

Boost Quaternions, Vectors, Matrices library
C++
80
star
51

coroutine

Boost.Coroutine
C++
79
star
52

signals2

Boost.org signals2 module
C++
74
star
53

config

Boost.org config module
C++
72
star
54

stl_interfaces

A C++14 and later CRTP template for defining iterators
C++
69
star
55

describe

A C++14 reflection library
C++
67
star
56

variant2

A never-valueless, strong guarantee implementation of std::variant
C++
66
star
57

date_time

Boost.org date_time module
C++
65
star
58

poly_collection

Fast containers of polymorphic objects.
C++
63
star
59

unordered

Boost.org unordered module
C++
62
star
60

static_string

A fixed capacity dynamically sized string
C++
62
star
61

type_traits

Boost.org type_traits module
C++
61
star
62

winapi

Windows API declarations without <windows.h>, for internal Boost use.
C++
58
star
63

atomic

Boost.Atomic
C++
57
star
64

mpi

Boost.org mpi module
C++
56
star
65

property_tree

Boost.org property_tree module
C++
56
star
66

intrusive

Boost.org intrusive module
C++
54
star
67

circular_buffer

Boost.org circular_buffer module
C++
53
star
68

sort

Boost.Sort
C++
50
star
69

optional

Boost.org optional module
C++
50
star
70

polygon

Boost.org polygon module
C++
48
star
71

fusion

Boost.org fusion module
C++
47
star
72

utility

Boost.org utility module
C++
47
star
73

variant

Boost.org variant module
C++
45
star
74

endian

Boost Endian library
C++
45
star
75

odeint

Boost.odeint
C++
44
star
76

range

Boost.org range module
C++
43
star
77

mpl

Boost.org mpl module
C++
43
star
78

predef

Boost.Predef (a Boost C++ Library)
C
43
star
79

iostreams

Boost.org iostreams module
C++
43
star
80

metaparse

A library for generating compile time parsers parsing embedded DSL code as part of the C++ compilation process
C++
42
star
81

multi_index

Boost.org multi_index module
C++
41
star
82

outcome

Provides very lightweight outcome<T> and result<T> (Boost edition)
C++
40
star
83

contract

Contract programming for C++
C++
39
star
84

pool

Boost.org pool module
C++
37
star
85

dynamic_bitset

Boost.org dynamic_bitset module
C++
36
star
86

system

Boost.org system module
C++
35
star
87

random

Boost.org random module
C++
34
star
88

assert

Boost.Assert
C++
32
star
89

container_hash

Generic hash function for STL style unordered containers
C++
32
star
90

any

Boost.org any module
C++
32
star
91

locale

Boost.Locale
C++
31
star
92

msm

Boost.org msm module
C++
30
star
93

phoenix

Boost.org phoenix module
C++
28
star
94

units

Boost.org units module
C++
28
star
95

bind

Boost.org bind module
C++
26
star
96

charconv

C++11 compatible charconv
C++
26
star
97

format

Boost.org format module
C++
25
star
98

multi_array

Boost.org multi_array module
C++
25
star
99

lexical_cast

General literal text conversions, such as an int represented as a string, or vice versa
C++
25
star
100

website

The boost website.
HTML
24
star