当前位置:   article > 正文

python使用Future、async、await、wait、gather、ensure_future、as_completed_asyncio ensure_future 和 wait

asyncio ensure_future 和 wait

参考:https://blog.csdn.net/weixin_45139605/article/details/90798253

参考:https://www.cnblogs.com/ssyfj/p/9219360.html

参考:https://www.cnblogs.com/xiao-xue-di/p/10274065.html

参考:https://www.jianshu.com/p/b5e347b3a17c

1.Future:

  1. # coding=utf-8
  2. import functools
  3. import asyncio
  4. import threading
  5. import time
  6. def printInfo(f, n):
  7. print("printInfo: {}, {}".format(f, n))
  8. # f.set_result("ok")
  9. async def one(allDone):
  10. print("one: start")
  11. allDone.add_done_callback(functools.partial(printInfo, n="i1"))
  12. allDone.add_done_callback(functools.partial(printInfo, n="i2"))
  13. print("one: middle")
  14. # allDone.set_result("ok")
  15. print("one: end")
  16. async def deal(loop, allDone):
  17. print("deal: begin")
  18. # loop.call_soon(printInfo, allDone, "i3")
  19. # loop.call_later(3, printInfo, allDone, "i4")
  20. await one(allDone)
  21. start = time.time()
  22. def wait(n):
  23. print("wait: n={}, {}".format(n, time.time()-start))
  24. allDone.set_result("ok")
  25. print("wait end")
  26. loop.call_later(2, wait, "i5")
  27. print("deal: middle {}".format(allDone))
  28. await allDone
  29. print("deal: second {}".format(allDone))
  30. print("deal: end")
  31. if __name__ == "__main__":
  32. loop = asyncio.get_event_loop()
  33. try:
  34. allDone = asyncio.Future()
  35. loop.run_until_complete(deal(loop, allDone))
  36. print("loop end")
  37. finally:
  38. loop.close()

结果:

  1. deal: begin
  2. one: start
  3. one: middle
  4. one: end
  5. deal: middle <Future pending cb=[printInfo(n='i1')() at e:\study\py\async\asyn.py:10, printInfo(n='i2')() at e:\study\py\async\asyn.py:10]>
  6. wait: n=i5, 2.0034987926483154
  7. wait end
  8. printInfo: <Future finished result='ok'>, i1
  9. printInfo: <Future finished result='ok'>, i2
  10. deal: second <Future finished result='ok'>
  11. deal: end
  12. loop end
  13. PS E:\study\py\async>

2.多任务:

  1. # coding=utf-8
  2. import asyncio
  3. import threading
  4. import datetime
  5. async def hello(name):
  6. for n in range(3):
  7. print("hello: start {},{}, {}".format(
  8. name, n, threading.currentThread()))
  9. await asyncio.sleep(1)
  10. print("hello: endtt {},{}, {}".format(
  11. name, n, threading.currentThread()))
  12. if __name__ == "__main__":
  13. loo
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/102725
推荐阅读
相关标签
  

闽ICP备14008679号