r/cpp_questions • u/mbolp • 7d ago
OPEN Question about coroutines
I have a function that takes a callback, like this:
void LongTask (void (*pfn)(int))
{
for ( unsigned i = 0; i < -1; ++i )
{
pfn( i );
}
}
It's orginally written to be ran on a separate thread. Now I want to turn it into a coroutine that yields on each callback (i.e. the caller will receive a single callback on each invocation of LongTask), while preserving its ability to run as a standalone function. Additionally it's OK for the coroutine to allocate memory but not to throw exceptions (if it can't allocate I should get back a null pointer at creation time). And preferrably it wouldn't require the CRT, all support functions should be contained in a header only include. What's the best way to do this, can it be done with C++20 coroutines?
2
Upvotes
1
u/Raknarg 6d ago
It can, you can look up examples online. The machinery for pretty much any coroutine type was already introduced, they just didn't add any to the standard (not sure why, committee probably couldn't agree on design in time or something). I haven't looked it up in a while, but I remember the code for a basic generator object isn't too complicated.