1 看起来是有点异步的意思,实际上还是一个多线程
from threading import Thread
import time
def async(func):
def wrapper(*args,**kwargs):
t = Thread(target=func,args=args,kwargs=kwargs)
t.start()
return wrapper
@async
def tests():
time.sleep(5)
print('ssss')
if __name__ == '__main__':
tests()
2 回调
import asyncio
async def do_some_work(x):
print('Waiting '+str(x))
await asyncio.sleep(x)
def done_callback(futu):
print('Done')
def huidiao():
""" 回调 """
loop = asyncio.get_event_loop()
futu = asyncio.ensure_future(do_some_work(3))
futu.add_done_callback(done_callback)
loop.run_until_complete(futu)
huidiao()
3 单个协程
import asyncio
async def do_some_work(x):
print('Waiting '+str(x))
await asyncio.sleep(x)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(do_some_work(1))
loop.close()
4 async / await 多个协程
import asyncio
async def do_some_work(x):
print('Waiting '+str(x))
await asyncio.sleep(x)
def many(size):
""" 多个协程 """
coros = [do_some_work(3) for i in range(size)]
# loop.run_until_complete(asyncio.wait(coros))
loop.run_until_complete(asyncio.gather(*coros))
if __name__ == '__main__':
many(10000) # 执行10000次
# 如果使用循环执行 do_some_work 函数,将耗费8个小时
# 如果使用多线程,由于线程的限制,一台32位的电脑也只能开启2000个以内的线程
# 而此程序仅仅执行了3秒钟