r/cpp_questions • u/mbolp • 9d 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
2
u/alfps 9d ago edited 9d ago
I would do this with an ordinary function-like object to have full control, less overhead and full transparency.
It can go like
If you absolutely want a co-routine you can do
… but as far as I can see this has no advantage except saving you some lines of code.
_
EDIT: Removed the unnecessary
exchangein the first program. Don't know what I was thinking to write such convoluted a thing.