HorseyWorsey@the_stables.com wrote:
> Coroutines should have stayed in the microsoft world, not added to the C++
> standard. They're a solution looking for a problem.
Coroutines do solve certain problems. It's just that very few people have
ever heard of them, and they are, for some reason, generally very poorly
explained and somewhat hard to understand.
One of the major applications of coroutines is, essentially, being able to
return from a function at any given point (ie. at any point in a function
you can put a command to "return to the caller") and then the calling
code can then tell the function to continue from where it left off.
Coroutines help in, essentially, storing the entire state of the function,
so that it can continue from that exact point, using the exact same state.
Ie. execution can continue from that point forward as if the function
hadn't been exited at all.
Coroutines are compared to cooperative multitasking, and in this sense
they indeed are very similar: In cooperative multitasking at certain
points you can "yield" the execution to the OS, which then later can
return the execution back to that yield point, which will then continue
as if nothing had happened. The entire state of the process is automatically
preserved so that it can continue normally.
You *can* achieve the same effect as coroutines without them, but it
requires you to manually create the data containers where all the
necessary variables are stored so that execution can continue from
the point where it left, and you have to manually create jump statements
to wherever there are these yield points. (The more yield points there
are in your "coroutine", the more conditional gotos are required.)
One practical example of where a coroutine is useful is a library that
decompresses compressed data from a file into a buffer of fixed size.
Whenever the buffer gets full, execution is returned to the caller
for it to consume the contents of the buffer, after which the
execution is returned to the decompressor, which continues from
where it left off. However, since the buffer can typically get full at
several points in the decompressor code, even in the middle of eg.
expanding a block of data, the decompressor needs to somehow store
its exact state in order to know how to continue with the decompression
once execution is resumed. There may be several different places in
the decompression code where stuff is written to the buffer, and at
any moment the buffer may get full. Coroutines can make this whole
thing a lot simpler, as at any point you can just add a yield, with
essentially no extra work to store the state of the decompressor.