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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

程序员老华   2022-12-06 我要评论

使用 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 这个装饰器不会预激协程。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们