iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python使用asyncio包处理并发的实现代码
  • 329
分享到

Python使用asyncio包处理并发的实现代码

Python asyncio包Python asyncio包处理并发 2022-12-08 20:12:23 329人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

使用 asyncio 包处理并发 asyncio包:使用事件循环驱动的协程实现并发。 线程与协程的对比 '\ thinking' 旋转等待效果 In [1]: imp

使用 asyncio 包处理并发

asyncio包:使用事件循环驱动的协程实现并发。

线程与协程的对比

'\ thinking' 旋转等待效果

In [1]: import threading
 
In [2]: import itertools
 
In [3]: import time,sys
 
In [4]: class Signal:  # 定义一个简单的可变对象;Go 属性 从外部控制线程
   ...:     go = True
 
In [5]: def spin(msg,signal):
   ...:     w,flush = sys.stdout.write,sys.stdout.flush
   ...:     for char in itertools.cycle('|/-\\'):  # 从序列中反复不断的生成元素
   ...:         status = char + ' ' + msg
   ...:         w(status)
   ...:         flush()
   ...:         w('\x08' * len(status))  # 退格键:\x08 文本动画的诀窍所在
   ...:         time.sleep(1)
   ...:         if not signal.go:
   ...:             break
   ...:     w(' ' * len(status) + '\x08' * len(status))
 
In [6]: def slow():
   ...:     time.sleep(3)
   ...:     return 42
 
In [9]: def super():
   ...:     signal = Signal()
   ...:     sp = threading.Thread(target=spin,args=('thinking',signal))
   ...:     print('============')
   ...:     sp.start()
   ...:     res = slow()
   ...:     signal.go = False
   ...:     sp.join()
   ...:     return res

注意:python 没有提供终止线程的 api ,这是有意为之的。若想关闭线程,必须给线程发送消息。这里用的是 signal.go 属性。干净的规则的退出。

适合 asyncio API 的协程:

1 定义体必须使用 yield from ,而不能使用 yield

2 协程要由调用方驱动,并由调用方通过 yield from 调用

3 或者把协程传给 asyncio 包中的某个函数,比如 asyncio.async()

4 @asyncio.coroutine 装饰器应该用在协程上

asyncio 实现 动画效果

In [1]: import asyncio
 
In [3]: import itertools
 
In [4]: import sys
 
# 交给 asyncio 处理的协程需要使用该装饰器装饰。这不是强制要求,但是强烈建议这么做。
In [5]: @asyncio.coroutine
   ...: def spin(msg):  # 不需要多线程的关闭参数
   ...:     w,flush = sys.stdout.write, sys.stdout.flush
   ...:     for char in itertools.cycle('|/-\\'):
   ...:         status = char + ' ' + msg
   ...:         w(status)
   ...:         flush()
   ...:         w('\x08' * len(status))
   ...:         try:
   ...:             yield from asyncio.sleep(.1)  # 不会阻塞事件循环
                # spin 函数苏醒后,取消请求 异常,退出循环
   ...:         except asyncio.CancelledError:
   ...:             break
   ...:     write(' ' * len(status) + '\x08' * len(status))
   ...:
 
In [6]: @asyncio.coroutine
   ...: def slow():
            # 把控制权交给主循环,休眠结束后,结束这个协程
   ...:     yield from asyncio.sleep(3)
   ...:     return 42
   ...:
 
In [9]: @asyncio.coroutine
   ...: def sup():
            # asyncio 排定spin协程的运行时间,封装成一个 Task对象 sp
   ...:     sp = asyncio.async(spin('thinking!'))
   ...:     print('spin obj:',sp)
            # sup 也是协程,因此,可以使用 yield from 驱动 slow()
   ...:     res = yield from slow()
            sp.cancel()
   ...:     return res
   ...:
 
In [10]: def main():
    ...:     loop = asyncio.get_event_loop()
    ...:     res = loop.run_until_complete(sup())
    ...:     loop.close()
    ...:     print('answer:',res)
    ...:
 
In [11]: main()
D:\python36\Scripts\iPython:3: DeprecationWarning: asyncio.async() function is deprecated, use ensure_future()
spin obj: <Task pending coro=<spin() running at <ipython-input-5-0304845f34e1>:1>>
answer: 42!

除非想阻塞主线程,从而冻结事件循环或整个应用,否则不要在 asyncio 协程中使用 time.sleep() 。如果协程需要一段时间内什么也不做,应该使用 yield from asyncio.sleep() 。

@asyncio.coroutine 装饰器不是强制要求,但是强烈建议这么做,因为这样能

1 把协程凸显出来,有助于调试。

2 如果还未产出值,协程就被垃圾回收了(意味着有操作未完成,因此有可能是个缺陷),那就可以发出警告了。

3 这个装饰器不会预激协程。

到此这篇关于Python使用asyncio包处理并发的实现代码的文章就介绍到这了,更多相关Python asyncio包内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Python使用asyncio包处理并发的实现代码

本文链接: https://www.lsjlt.com/news/174395.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作