3 ms·
very informally, they're good for the kind of problem where it would be nice to structure your code as if you're using threads, but you have a simple sequence o
by andrewcooke 13y ago
very informally, they're good for the kind of problem where it would be nice to structure your code as if you're using threads, but you have a simple sequence of actions so don't need the asynchronous aspect of threads or the worry that goes with them + mutable state.
for example, in the matasano crypto challenge i needed to simulate a message protocol between various actors (and then break it). i could have written client and server as separate threaded entities, but it was simpler to just have them each be a coroutine.
think of them like thread, state and bi-directional queue, in one easy package.
another example is lazy sequences. you could start up a separate thread that generates the sequences, but then you need to talk to it, throttle it in some way, and close it down. using a generator (a simple co-routine) you can still have your code for generating the sequence in one clean place, but it's easier to call and control.
if you've ever thought "it would be kinda cool if threads were simple, so i could structure my code like..." then you probably would have appreciated a coroutine.
[update: blog post on the protocol bit - http://www.acooke.org/cute/UsingCorou0.html http://www.acooke.org/cute/UsingCorou0.html - although really it doesn't say much more than the above]
- tel 13y agoCool, I've been expecting a chance to do coroutine-based modeling of crypto protocols in those challenges, but haven't been able to devote any time to going through them.