fork(1) download
  1. import asyncio
  2.  
  3. @asyncio.coroutine
  4. def task(dur):
  5. print("task start")
  6. yield from asyncio.sleep(dur) # time-consuming task
  7. print("task finished")
  8. return "result of the %s task" % ['long','short'][dur%2]
  9.  
  10. def main():
  11. print("starting a long task")
  12. x = asyncio.async(task(4)) # start the task
  13. yield from asyncio.sleep(0.5) # do something else
  14. print("half a sec later")
  15. yield from asyncio.sleep(1) # do something else again
  16. print("a sec more")
  17. result = yield from x # now we need to use the result
  18. print("yielded result: %s" % result)
  19. yield from asyncio.sleep(1)
  20. # But what if the task is short?
  21. print("starting a short task")
  22. x = asyncio.async(task(1)) # start the task
  23. yield from asyncio.sleep(0.5) # do something else
  24. print("half a sec later")
  25. yield from asyncio.sleep(1) # do something else again
  26. print("a sec more")
  27. result = yield from x # now we need to use the result
  28. print("yielded result: %s" % result)
  29. yield from asyncio.sleep(1)
  30. print("finished")
  31.  
  32. loop = asyncio.get_event_loop()
  33. loop.run_until_complete(main())
Success #stdin #stdout 0.12s 15768KB
stdin
Standard input is empty
stdout
starting a long task
task start
half a sec later
a sec more
task finished
yielded result: result of the long task
starting a short task
task start
half a sec later
task finished
a sec more
yielded result: result of the short task
finished