Paavo Helde <
ees...@osa.pri.ee> wrote:
>> Co-routines is the undisputed winner, hands down. A solution in search
>> of a problem.
>
> More like a solution which you need to poorly reinvent or work around
> when you don't realize you have *this* problem.
>
> If you don't have use for co-routines this does not mean nobody does.
> For example, I have not found use for std::list and I'm not complaining.
It took me some time to understand what coroutines are good for, but
once I figured out this practical example, I think it' makes it quite
clear. (I have mentioned this in the past, but I suppose it doesn't
hurt repeating.)
Suppose you are decompressing a file (or compressed data that's
coming in or whatever). You have a fixed-sized array into which
you are storing the decompressed data. The idea is that once the
array gets full, you should call some "consumer" code that handles
the uncompressed data (and thus "empties" the array of it), after
which you continue decompressing more data into it.
The thing is, compressed data tends to be in some kind of chunks,
ie. when you decompress one "unit" if compressed data, the resulting
decompressed data may not fit neatly in the array, filling it
completely (or fitting inside it in the first place, even if the
array was empty). You would need to partially decompress this
chunk of compressed data and fill the array with the decompressed
data, call the "consumer" code, and then continue decompressing
from where you left (now filling the array from the beginning).
In other words, you need to be able to stop decompressing somewhere
in the middle of your decompression routine, call the outside code,
and then resume from where you left.
Normally this means that you need to store the entire state of your
decompressor somewhere, and then code the logic that allows you to
continue from where you left off. This becomes quite complicated
if there are many points in the decompressor code where the output
array may get full and thus it needs to stop, call the "consumer",
and then continue.
This is where coroutines step in to largely automatize this entire
process. At any point in your decompressor, if the output array may
get full, you simply "yield", and then continue as normal. You don't
need to keep the entire decompressor state stored somewhere, you don't
need to remember which "yield" point you were last in, you don't need
to code any logic to jump back to that particular "yield" point.
Coroutines take care of all that automatically for you.
It is, of course, perfectly possible to do all this without
coroutines, but it's much more laborious. Coroutines automatize
most of this.