import asyncio
import random
@asyncio.coroutine
def main():
pool = asyncio.Queue()
pool.put_nowait(1)
pool.put_nowait(2)
pool.put_nowait(3)
@asyncio.coroutine
def pooled(coro):
id = yield from pool.get()
print('+ task')
try:
return (yield from coro)
finally:
print('- task')
pool.put_nowait(id)
tasks = [
pooled(asyncio.sleep(random.randint(1, 2)))
for i in range(10)
]
yield from asyncio.wait(tasks)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
aW1wb3J0IGFzeW5jaW8KaW1wb3J0IHJhbmRvbQoKCkBhc3luY2lvLmNvcm91dGluZQpkZWYgbWFpbigpOgogICAgcG9vbCA9IGFzeW5jaW8uUXVldWUoKQogICAgcG9vbC5wdXRfbm93YWl0KDEpCiAgICBwb29sLnB1dF9ub3dhaXQoMikKICAgIHBvb2wucHV0X25vd2FpdCgzKQoKICAgIEBhc3luY2lvLmNvcm91dGluZQogICAgZGVmIHBvb2xlZChjb3JvKToKICAgICAgICBpZCA9IHlpZWxkIGZyb20gcG9vbC5nZXQoKQogICAgICAgIHByaW50KCcrIHRhc2snKQogICAgICAgIHRyeToKICAgICAgICAgICAgcmV0dXJuICh5aWVsZCBmcm9tIGNvcm8pCiAgICAgICAgZmluYWxseToKICAgICAgICAgICAgcHJpbnQoJy0gdGFzaycpCiAgICAgICAgICAgIHBvb2wucHV0X25vd2FpdChpZCkKCiAgICB0YXNrcyA9IFsKICAgICAgICBwb29sZWQoYXN5bmNpby5zbGVlcChyYW5kb20ucmFuZGludCgxLCAyKSkpCiAgICAgICAgZm9yIGkgaW4gcmFuZ2UoMTApCiAgICBdCgogICAgeWllbGQgZnJvbSBhc3luY2lvLndhaXQodGFza3MpCgoKbG9vcCA9IGFzeW5jaW8uZ2V0X2V2ZW50X2xvb3AoKQpsb29wLnJ1bl91bnRpbF9jb21wbGV0ZShtYWluKCkp