Python使用asyncio包處理并發(fā)的實現代碼
使用 asyncio 包處理并發(fā)
asyncio包:使用事件循環(huán)驅動的協(xié)程實現并發(fā)。
線程與協(xié)程的對比
'\ 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 ,這是有意為之的。若想關閉線程,必須給線程發(fā)送消息。這里用的是 signal.go 屬性。干凈的規(guī)則的退出。
適合 asyncio API 的協(xié)程:
1 定義體必須使用 yield from ,而不能使用 yield
2 協(xié)程要由調用方驅動,并由調用方通過 yield from 調用
3 或者把協(xié)程傳給 asyncio 包中的某個函數,比如 asyncio.async()
4 @asyncio.coroutine 裝飾器應該用在協(xié)程上
asyncio 實現 動畫效果
In [1]: import asyncio
In [3]: import itertools
In [4]: import sys
# 交給 asyncio 處理的協(xié)程需要使用該裝飾器裝飾。這不是強制要求,但是強烈建議這么做。
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) # 不會阻塞事件循環(huán)
# spin 函數蘇醒后,取消請求 異常,退出循環(huán)
...: except asyncio.CancelledError:
...: break
...: write(' ' * len(status) + '\x08' * len(status))
...:
In [6]: @asyncio.coroutine
...: def slow():
# 把控制權交給主循環(huán),休眠結束后,結束這個協(xié)程
...: yield from asyncio.sleep(3)
...: return 42
...:
In [9]: @asyncio.coroutine
...: def sup():
# asyncio 排定spin協(xié)程的運行時間,封裝成一個 Task對象 sp
...: sp = asyncio.async(spin('thinking!'))
...: print('spin obj:',sp)
# sup 也是協(xié)程,因此,可以使用 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!
除非想阻塞主線程,從而凍結事件循環(huán)或整個應用,否則不要在 asyncio 協(xié)程中使用 time.sleep() 。如果協(xié)程需要一段時間內什么也不做,應該使用 yield from asyncio.sleep() 。
@asyncio.coroutine 裝飾器不是強制要求,但是強烈建議這么做,因為這樣能
1 把協(xié)程凸顯出來,有助于調試。
2 如果還未產出值,協(xié)程就被垃圾回收了(意味著有操作未完成,因此有可能是個缺陷),那就可以發(fā)出警告了。
3 這個裝飾器不會預激協(xié)程。
到此這篇關于Python使用asyncio包處理并發(fā)的實現代碼的文章就介紹到這了,更多相關Python asyncio包內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python-Tkinter Text輸入內容在界面顯示的實例
今天小編就為大家分享一篇Python-Tkinter Text輸入內容在界面顯示的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07

