C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Asyncio: We use get_event_loop to begin adding methods to run. We create a tasks list with ensure_future calls.
Run: We call run_until_complete with the result of gather() to execute all our methods in parallel.
Sleep: The methods would not yield to each other without the "yield from asyncio.sleep" statement.
Python program that uses asyncio
import asyncio
@asyncio.coroutine
def logic(max):
# This method runs some logic in a loop.
# ... The max is specified as an argument.
count = 0
for i in range(1, max):
count += i
count = count / i
# Provide a chance to run other methods.
yield from asyncio.sleep(1)
# Finished.
print("Logic result", max, count)
# Get our event loop.
loop = asyncio.get_event_loop()
# Call logic method four times.
tasks = [
asyncio.ensure_future(logic(5)),
asyncio.ensure_future(logic(20)),
asyncio.ensure_future(logic(10)),
asyncio.ensure_future(logic(1))]
# Run until all logic methods have completed.
# ... The sleep call will allow all to run in parallel.
loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
Output
Logic result 1 0
Logic result 5 1.375
Logic result 10 1.1274057539682538
Logic result 20 1.0557390762436003
But: Having asleep call gives other methods a chance to run. The other methods run when asyncio.sleep is called.