|
|
|
|
|
by throwaway_94404
634 days ago
|
|
I just can't get my brain around coroutines. Can anyone recommend a good tutorial or resource for me to read. I find it so frustrating as I don't think it's necessarily a complex subject but my brain just doesn't get it. Related perhaps but many (many, many) years ago, when learning BASIC, I assumed GOSUB went off and started executing the code in the subroutine as well as the rest of the inline code. That suggests to me that I should perhaps have a deeper understanding of this but I really don't... |
|
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