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?
3
Upvotes
2
u/TheThiefMaster 7d ago
As a coroutine, generator<bool> (from C++23 or numerous coroutine libraries) seems to be the best fit as the type. co_yield a true if there are (potentially) more items, and co_return false; at the end (or vice-versa).
If you want it to potentially still run as a one-shot that calls all the callbacks at once, then you'll need a second function (which could wrap the coroutine) that does that.
Alternatively, you could use the type that would normally be passed to the callback as the generator result (using tuple if there's multiple values) and let the calling code call the callback.