import asyncio
import random
@asyncio.coroutine
def main():
pool = asyncio.Semaphore(3)
@asyncio.coroutine
def pooled(coro):
with (yield from pool):
print("+ task")
try:
return (yield from coro)
finally:
print("- task")
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())
aW1wb3J0IGFzeW5jaW8KaW1wb3J0IHJhbmRvbQoKCkBhc3luY2lvLmNvcm91dGluZQpkZWYgbWFpbigpOgogICAgcG9vbCA9IGFzeW5jaW8uU2VtYXBob3JlKDMpCgogICAgQGFzeW5jaW8uY29yb3V0aW5lCiAgICBkZWYgcG9vbGVkKGNvcm8pOgogICAgICAgIHdpdGggKHlpZWxkIGZyb20gcG9vbCk6CiAgICAgICAgICAgIHByaW50KCIrIHRhc2siKQogICAgICAgICAgICB0cnk6CiAgICAgICAgICAgICAgICByZXR1cm4gKHlpZWxkIGZyb20gY29ybykKICAgICAgICAgICAgZmluYWxseToKICAgICAgICAgICAgICAgIHByaW50KCItIHRhc2siKQoKICAgIHRhc2tzID0gWwogICAgICAgIHBvb2xlZChhc3luY2lvLnNsZWVwKHJhbmRvbS5yYW5kaW50KDEsIDIpKSkKICAgICAgICBmb3IgaSBpbiByYW5nZSgxMCkKICAgIF0KCiAgICB5aWVsZCBmcm9tIGFzeW5jaW8ud2FpdCh0YXNrcykKCgpsb29wID0gYXN5bmNpby5nZXRfZXZlbnRfbG9vcCgpCmxvb3AucnVuX3VudGlsX2NvbXBsZXRlKG1haW4oKSk=