Our great sponsors
-
InfluxDB
Power Real-Time Data Analytics at Scale. Get real-time insights from all types of time series data with InfluxDB. Ingest, query, and analyze billions of data points in real-time with unbounded cardinality.
Some notes:
- C++20 coroutines are stackless, meaning that multiple coroutines will share a single OS thread stack. This is non-obvious when you first learn about them because they look just like functions. All your local function (coroutine) variables are captured and allocated as part of the coroutine context for you.
- C++20 coroutine functions are just ordinary functions, and can be called from C code. In fact, coroutine contexts can be cast to and from void* to enable great integration with C.
- There's currently no utility in the C++20 standard library for using C++20 coroutines to defer work. std::future<> only works on threaded code, and you can't easily use std::function. See Lewis Bakers 'task' class for a usable mechanism https://github.com/lewissbaker/cppcoro#taskt
Or take advantage of the ABI of the runtime, and use assembly. [1] Yeah, not portable. But using setjmp()/longjmp() has issues as well (way too easy to mess it up because it doesn't do what you think it's doing).
[1] https://github.com/spc476/C-Coroutines
Stackless means when you resume a coroutine you're still using the same OS thread stack. Coroutine contexts/activation records are conceptually heap allocated (although in some cases that can be optimized away).
You can use coroutines for what you say, but there are no execution contexts (like a thread pool or an event loop) in C++20 standard library in which to execute coroutines, so to async I/O you need to use a library or DIY. This will come later as part of the Executors proposal.
You can currently use C++ native coroutines withe ASIO library, but this is probably subject to quite a bit of API churn in the future:
https://www.boost.org/doc/libs/1_75_0/doc/html/boost_asio/ov...
You can also wrap things like ASIO yourself. I did this in 2018 when I was learning about C++ coroutines to create a simple telnet based chatroom:
https://github.com/heavenlake/coro-chat/blob/master/chat.cpp
Note that this code is likely garbage by todays standards.
Keep in mind that these is a really basic building block where you can bring your own runtime and hook coroutines into it, not something that is at all usable out of the box. This is exacerbated by the fact that the C++ standard library is still lacking support for non-blocking futures/promises.
To see how it can be used for actual asynchronous operations on a thread pool, take a look at asyncly, which I co-authored:
https://github.com/LogMeIn/asyncly/blob/master/Test/Unit/fut...