A library of C++ coroutine abstractions for the coroutines TS
A library of C++ coroutine abstractions for the coroutines TS
The 'cppcoro' library provides a large set of general-purpose primitives for making use of the coroutines TS proposal described in N4680.
These include:
cancellation_tokencancellation_sourcecancellation_registrationThis library is an experimental library that is exploring the space of high-performance, scalable asynchronous programming abstractions that can be built on top of the C++ coroutines proposal.
It has been open-sourced in the hope that others will find it useful and that the C++ community can provide feedback on it and ways to improve it.
It requires a compiler that supports the coroutines TS:
The Linux version is functional except for the io_context and file I/O related classes which have not yet been implemented for Linux (see issue #15 for more info).
task<T>A task represents an asynchronous computation that is executed lazily in that the execution of the coroutine does not start until the task is awaited.
Example:
…API Overview:
…You can create a task<T> object by calling a coroutine function that returns
a task<T>.
The coroutine must contain a usage of either co_await or co_return.
Note that a task<T> coroutine may not use the co_yield keyword.
When a coroutine that returns a task<T> is called, a coroutine frame
is allocated if necessary and the parameters are captured in the coroutine
frame. The coroutine is suspended at the start of the coroutine body and
execution is returned to the caller and a task<T> value that represents
the asynchronous computation is returned from the function call.
The coroutine body will start executing when the task<T> value is
co_awaited. This will suspend the awaiting coroutine and start execution
of the coroutine associated with the awaited task<T> value.
The awaiting coroutine will later be resumed on the thread that completes
execution of the awaited task<T>'s coroutine. ie. the thread that
executes the co_return or that throws an unhandled exception that terminates
execution of the coroutine.
If the task has already run to completion then awaiting it again will obtain the already-computed result without suspending the awaiting coroutine.
If the task object is destroyed before it is awaited then the coroutine
never executes and the destructor simply destructs the captured parameters
and frees any memory used by the coroutine frame.
shared_task<T>The shared_task<T> class is a coroutine type that yields a single value
asynchronously.
It is 'lazy' in that execution of the task does not start until it is awaited by some coroutine.
It is 'shared' in that the task value can be copied, allowing multiple references to the result of the task to be created. It also allows multiple coroutines to concurrently await the result.
The task will start executing on the thread that first co_awaits the task.
Subsequent awaiters will either be suspended and be queued for resumption
when the task completes or will continue synchronously if the task has
already run to completion.
If an awaiter is suspended while waiting for the task to complete then
it will be resumed on the thread that completes execution of the task.
ie. the thread that executes the co_return or that throws the unhandled
exception that terminates execution of the coroutine.
API Summary
…All const-methods on shared_task<T> are safe to call concurrently with other
const-methods on the same instance from multiple threads. It is not safe to call
non-const methods of shared_task<T> concurrently with any other method on the
same instance of a shared_task<T>.
task<T>The shared_task<T> class is similar to task<T> in that the task does
not start execution immediately upon the coroutine function being called.
The task only starts executing when it is first awaited.
It differs from task<T> in that the resulting task object can be copied,
allowing multiple task objects to reference the same asynchronous result.
It also supports multiple coroutines concurrently awaiting the result of the task.
The trade-off is that the result is always an l-value reference to the result, never an r-value reference (since the result may be shared) which may limit ability to move-construct the result into a local variable. It also has a slightly higher run-time cost due to the need to maintain a reference count and support multiple awaiters.
generator<T>A generator represents a coroutine type that produces a sequence of values of type, T,
where values are produced lazily and synchronously.
The coroutine body is able to yield values of type T using the co_yield keyword.
Note, however, that the coroutine body is not able to use the co_await keyword;
values must be produced synchronously.
For example:
cppcoro::generator<const std::uint64_t> fibonacci()
{
std::uint64_t a = 0, b = 1;
while (true)
{
co_yield b;
auto tmp = a;
a = b;
b += tmp;
}
}
void usage()
{
for (auto i : fibonacci())
{
if (i > 1'000'000) break;
std::cout << i << std::endl;
}
}When a coroutine function returning a generator<T> is called the coroutine is created initially suspended.
Execution of the coroutine enters the coroutine body when the generator<T>::begin() method is called and continues until
either the first co_yield statement is reached or the coroutine runs to completion.
If the returned iterator is not equal to the end() iterator then dereferencing the iterator will
return a reference to the value passed to the co_yield statement.
Calling operator++() on the iterator will resume execution of the coroutine and continue until
either the next co_yield point is reached or the coroutine runs to completion().
Any unhandled exceptions thrown by the coroutine will propagate out of the begin() or
operator++() calls to the caller.
API Summary:
…recursive_generator<T>A recursive_generator is similar to a generator except that it is designed to more efficiently
support yielding the elements of a nested sequence as elements of an outer sequence.
In addition to being able to co_yield a value of type T you can also co_yield a value of type recursive_generator<T>.
When you co_yield a recursive_generator<T> value the all elements of the yielded generator are yielded as elements of the current generator.
The current coroutine is suspended until the consumer has finished consuming all elements of the nested generator, after which point execution
of the current coroutine will resume execution to produce the next element.
The benefit of recursive_generator<T> over generator<T> for iterating over recursive data-structures is that the iterator::operator++()
is able to directly resume the leaf-most coroutine to produce the next element, rather than having to resume/suspend O(depth) coroutines for each element.
The down-side is that there is additional overhead
For example:
// Lists the immediate contents of a directory.
cppcoro::generator<dir_entry> list_directory(std::filesystem::path path);
cppcoro::recursive_generator<dir_entry> list_directory_recursive(std::filesystem::path path)
{
for (auto& entry : list_directory(path))
{
co_yield entry;
if (entry.is_directory())
{
co_yield list_directory_recursive(entry.path());
}
}
}Note that applying the fmap() operator to a recursive_generator<T> will yield a generator<U>
type rather than a recursive_generator<U>. This is because uses of fmap are generally not used
in recursive contexts and we try to avoid the extra overhead incurred by recursive_generator.
async_generator<T>An async_generator represents a coroutine type that produces a sequence of values of type, T, where values are produced lazily and values may be produced asynchronously.
The coroutine body is able to use both co_await and co_yield expressions.
Consumers of the generator can use a for co_await range-based for-loop to consume the values.
Example
cppcoro::async_generator<int> ticker(int count, threadpool& tp)
{
for (int i = 0; i < count; ++i)
{
co_await tp.delay(std::chrono::seconds(1));
co_yield i;
}
}
cppcoro::task<> consumer(threadpool& tp)
{
auto sequence = ticker(10, tp);
for co_await(std::uint32_t i : sequence)
{
std::cout << "Tick " << i << std::endl;
}
}API Summary
…When the async_generator object is destructed it requests cancellation of the underlying coroutine.
If the coroutine has already run to completion or is currently suspended in a co_yield expression
then the coroutine is destroyed immediately. Otherwise, the coroutine will continue execution until
it either runs to completion or reaches the next co_yield expression.
When the coroutine frame is destroyed the destructors of all variables in scope at that point will be executed to ensure the resources of the generator are cleaned up.
Note that the caller must ensure that the async_generator object must not be destroyed while a
consumer coroutine is executing a co_await expression waiting for the next item to be produced.
single_consumer_eventThis is a simple manual-reset event type that supports only a single coroutine awaiting it at a time. This can be used to
API Summary:
// <cppcoro/single_consumer_event.hpp>
namespace cppcoro
{
class single_consumer_event
{
public:
single_consumer_event(bool initiallySet = false) noexcept;
bool is_set() const noexcept;
void set();
void reset() noexcept;
Awaiter<void> operator co_await() const noexcept;
};
}Example:
#include <cppcoro/single_consumer_event.hpp>
cppcoro::single_consumer_event event;No open issues yet, or sync has not completed.