赞
踩
参考: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
- # coding=utf-8
-
-
- import functools
- import asyncio
- import threading
- import time
-
-
- def printInfo(f, n):
- print("printInfo: {}, {}".format(f, n))
- # f.set_result("ok")
-
-
- async def one(allDone):
- print("one: start")
- allDone.add_done_callback(functools.partial(printInfo, n="i1"))
- allDone.add_done_callback(functools.partial(printInfo, n="i2"))
- print("one: middle")
- # allDone.set_result("ok")
- print("one: end")
-
-
- async def deal(loop, allDone):
- print("deal: begin")
- # loop.call_soon(printInfo, allDone, "i3")
- # loop.call_later(3, printInfo, allDone, "i4")
- await one(allDone)
- start = time.time()
-
- def wait(n):
- print("wait: n={}, {}".format(n, time.time()-start))
- allDone.set_result("ok")
- print("wait end")
-
- loop.call_later(2, wait, "i5")
- print("deal: middle {}".format(allDone))
- await allDone
- print("deal: second {}".format(allDone))
- print("deal: end")
-
- if __name__ == "__main__":
- loop = asyncio.get_event_loop()
-
- try:
- allDone = asyncio.Future()
- loop.run_until_complete(deal(loop, allDone))
- print("loop end")
- finally:
- loop.close()
结果:
- deal: begin
- one: start
- one: middle
- one: end
- 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]>
- wait: n=i5, 2.0034987926483154
- wait end
- printInfo: <Future finished result='ok'>, i1
- printInfo: <Future finished result='ok'>, i2
- deal: second <Future finished result='ok'>
- deal: end
- loop end
- PS E:\study\py\async>
2.多任务:
- # coding=utf-8
-
-
- import asyncio
- import threading
- import datetime
-
-
- async def hello(name):
- for n in range(3):
- print("hello: start {},{}, {}".format(
- name, n, threading.currentThread()))
- await asyncio.sleep(1)
- print("hello: endtt {},{}, {}".format(
- name, n, threading.currentThread()))
-
- if __name__ == "__main__":
- loo
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。