• Python——使用asyncio包处理并发


    使用 asyncio 包处理并发

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

    线程与协程的对比

    '\ thinking' 旋转等待效果

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

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

    适合 asyncio API 的协程:

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

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

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

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

    asyncio 实现 动画效果

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

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

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

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

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

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

  • 相关阅读:
    反射机制了解
    libusb开源库使用说明
    [2022 强网杯] devnull 复现
    springboot系列(二十七):如何实现word携带图片导出?这你得会|超级详细,建议收藏
    亲手将TP-LINK路由器改装成交换机使用
    教程一 Energy 构建简单的Windows、Linux、MacOSX桌面应用
    Packet Tracer - 研究 DUAL FSM
    Unity2D创建帧动画片段
    linux常用指令
    java之流程控制
  • 原文地址:https://blog.csdn.net/m0_72557783/article/details/128188439