top | item 41649048

(no title)

singledigits | 1 year ago

I feel you! Coroutines can be tricky at first. I recommend Lewis Baker's blog about coroutines [1], which is detailed and insightful. Additionally, cppreference [2] is a great resource to understand how coroutines work in C++.

In a nutshell, C++ coroutines are almost like regular functions, except that they can be "paused" (suspended), and their state is stored on the heap so they can be resumed later. When you resume a coroutine, its state is loaded back, and execution continues from where it left off.

The complicated part comes from the interfaces through which you use coroutines in C++. Each coroutine needs to be associated with a promise object, which defines how the coroutine behaves (for example, what happens when you co_return a value). Then, there are awaiters, which define what happens when you co_await them. For example, C++ provides a built-in awaiter called suspend_always{}, which you can co_await to pause the coroutine.

If you take your time and go thoroughly through the blog and Cppreference, you'll definitely get the hang of it.

Hope this helps.

[1] https://lewissbaker.github.io/ [2] https://en.cppreference.com/w/cpp/language/coroutines

discuss

order

loeg|1 year ago

They're just green threads with some nice syntax sugar, right? Instead of an OS-level "pause" with a futex-wait or sleep (resumed by the kernel scheduler), they do an application-level pause and require some application-level scheduler. (But coroutines can still call library or kernel functions that block/sleep, breaking userspace scheduling?)

singledigits|1 year ago

Yes, exactly. Coroutines are one possible implementation of green threads. Once they are scheduled/loaded on an OS thread, they behave just like regular functions with their own call stack. This means they can indeed call blocking operations at the OS level. A possible approach to handle such operations would be to wrap the blocking call, suspend the coroutine, and then resume it once the operation is complete, perhaps by polling(checking for completion).