python3 Async/Await入门指南
生活随笔
收集整理的这篇文章主要介绍了
python3 Async/Await入门指南
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
有一个任务,多次执行一个函数,这个函数是阻塞的,阻塞原因是比如获取网络资源,这个时候该怎么办,一般来讲多线程是个不错的选择,python3.5以后提供了async可以让单线程达到相同效果。示例如下:
import threading import asyncioasync 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 asyncioasync 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')
总结
以上是生活随笔为你收集整理的python3 Async/Await入门指南的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: python3爬虫(9)分布式爬虫与对等
- 下一篇: Pythont特殊语法filter,ma