Most "active" coroutine library project?
Simon Forman
sajmikins at gmail.com
Fri Sep 25 15:25:32 EDT 2009
On Fri, Sep 25, 2009 at 2:07 PM, Jason Tackaberry <tack at urandom.ca> wrote:
> On Fri, 2009-09-25 at 15:42 +0000, Grant Edwards wrote:
>> You can't call a function that yields control back to the other
>> coroutine(s). By jumping through some hoops you can get the
>> same effect, but it's not very intuitive and it sort of "feels
>> wrong" that the main routine has to know ahead of time when
>> calling a function whether that function might need to yield or
>> not.
>
> Not directly, but you can simulate this, or at least some pseudo form of
> it which is useful in practice. I suppose you could call this "jumping
> through some hoops," but from the point of view of the coroutine, it can
> be done completely transparently, managed by the coroutine scheduler.
>
> In kaa, which I mentioned earlier, this might look like:
>
> import kaa
>
> @kaa.coroutine()
> def task(name):
> for i in range(10):
> print name, i
> yield kaa.NotFinished # kind of like a time slice
>
> @kaa.coroutine()
> def fetch_google():
> s = kaa.Socket()
> try:
> yield s.connect('google.com:80')
> except:
> print 'Connection failed'
> return
> yield s.write('GET / HTTP/1.1\nHost: google.com\n\n')
> yield (yield s.read())
>
> @kaa.coroutine()
> def orchestrate():
> task('apple')
> task('banana')
> page = yield fetch_google()
> print 'Fetched %d bytes' % len(page)
>
> orchestrate()
> kaa.main.run()
>
>
> The two task() coroutines spawned by orchestrate() continue to "run in
> the background" while any of the yields in fetch_google() are pending
> (waiting on some network resource).
>
> It's true that the yields in fetch_google() aren't yielding control
> _directly_ to one of the task() coroutines, but it _is_ doing so
> indirectly, via the coroutine scheduler, which runs inside the main
> loop.
>
> Cheers,
> Jason.
>
So Kaa is essentially implementing the trampoline function.
If I understand it correctly MyHDL does something similar (to
implement models of hardware components running concurrently.)
http://www.myhdl.org/
More information about the Python-list
mailing list