有一个任务,多次执行一个函数,这个函数是阻塞的,阻塞原因是比如获取网络资源,这个时候该怎么办,一般来讲多线程是个不错的选择,python3.5以后提供了async可以让单线程达到相同效果。示例如下:
import threading
import asyncio
async def hello():
print('Hello world! (%s)' % threading.currentThread())
await asyncio.sleep(10)
print('Hello again! (%s)' % threading.currentThread())
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
值得注意的是这个异步的数量可以非常的庞大,上百万都不会有什么问题,我们用下面的代码进行测试,
import threading
import asyncio
async def hello():
print('Hello world! (%s)' % threading.currentThread())
await asyncio.sleep(1)
print('Hello again! (%s)' % threading.currentThread())
try:
loop = asyncio.get_event_loop()
tasks = [hello() for i in range(1000*1000*1)]
loop.run_until_complete(asyncio.wait(tasks))
# loop.close()
except ValueError:
print('Async Error')