国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

python 使用事件對象asyncio.Event來同步協(xié)程的操作

瀏覽:57日期:2022-07-26 13:34:09

事件對象asyncio.Event是基于threading.Event來實現(xiàn)的。

事件可以一個信號觸發(fā)多個協(xié)程同步工作,

例子如下:

import asyncioimport functools def set_event(event): print(’setting event in callback’) event.set() async def coro1(event): print(’coro1 waiting for event’) await event.wait() print(’coro1 triggered’) async def coro2(event): print(’coro2 waiting for event’) await event.wait() print(’coro2 triggered’) async def main(loop): # Create a shared event event = asyncio.Event() print(’event start state: {}’.format(event.is_set())) loop.call_later( 0.1, functools.partial(set_event, event) ) await asyncio.wait([coro1(event), coro2(event)]) print(’event end state: {}’.format(event.is_set())) event_loop = asyncio.get_event_loop()try: event_loop.run_until_complete(main(event_loop))finally: event_loop.close()

輸出如下:

event start state: Falsecoro2 waiting for eventcoro1 waiting for eventsetting event in callbackcoro2 triggeredcoro1 triggeredevent end state: True

補充知識: python里使用協(xié)程來創(chuàng)建echo客戶端

在這個例子里使用asyncio.Protocol來創(chuàng)建一個echo客戶端,先導(dǎo)入庫asyncio和logging。

接著定義發(fā)送的消息MESSAGES。

創(chuàng)建連接服務(wù)器的地址SERVER_ADDRESS,接著創(chuàng)建EchoClient類,它是繼承asyncio.Protocol。

在這個類的構(gòu)造函數(shù)里,接收兩個參數(shù)messages和future,

messages是指定要發(fā)送的消息數(shù)據(jù),future是用來通知socket接收數(shù)據(jù)完成或者服務(wù)器關(guān)閉socket的事件通知,以便事件循環(huán)知道這個協(xié)程已經(jīng)完成了,就可以退出整個程序。

connection_made函數(shù)是當socket連接到服務(wù)器時調(diào)用,它就立即發(fā)送數(shù)據(jù)給服務(wù)器,數(shù)據(jù)發(fā)送完成之后發(fā)送了eof標記。

服務(wù)器收到數(shù)據(jù)和標志都回復(fù)客戶端,客戶端data_received函數(shù)接收數(shù)據(jù),eof_received函數(shù)接收結(jié)束標記。

connection_lost函數(shù)收到服務(wù)器斷開連接。

這行代碼:

client_completed = asyncio.Future()

創(chuàng)建一個協(xié)程完成的觸發(fā)事件。

由于event_loop.create_connection函數(shù)只能接收一個參數(shù),需要使用functools.partial來進行多個參數(shù)包裝成一個參數(shù)。

后面通過事件循環(huán)來運行協(xié)程。

import asyncioimport functoolsimport loggingimport sys MESSAGES = [ b’This is the message. ’, b’It will be sent ’, b’in parts.’,]SERVER_ADDRESS = (’localhost’, 10000) class EchoClient(asyncio.Protocol): def __init__(self, messages, future): super().__init__() self.messages = messages self.log = logging.getLogger(’EchoClient’) self.f = future def connection_made(self, transport): self.transport = transport self.address = transport.get_extra_info(’peername’) self.log.debug( ’connecting to {} port {}’.format(*self.address) ) # This could be transport.writelines() except that # would make it harder to show each part of the message # being sent. for msg in self.messages: transport.write(msg) self.log.debug(’sending {!r}’.format(msg)) if transport.can_write_eof(): transport.write_eof() def data_received(self, data): self.log.debug(’received {!r}’.format(data)) def eof_received(self): self.log.debug(’received EOF’) self.transport.close() if not self.f.done(): self.f.set_result(True) def connection_lost(self, exc): self.log.debug(’server closed connection’) self.transport.close() if not self.f.done(): self.f.set_result(True) super().connection_lost(exc) logging.basicConfig( level=logging.DEBUG, format=’%(name)s: %(message)s’, stream=sys.stderr,)log = logging.getLogger(’main’) event_loop = asyncio.get_event_loop() client_completed = asyncio.Future() client_factory = functools.partial( EchoClient, messages=MESSAGES, future=client_completed,)factory_coroutine = event_loop.create_connection( client_factory, *SERVER_ADDRESS,) log.debug(’waiting for client to complete’)try: event_loop.run_until_complete(factory_coroutine) event_loop.run_until_complete(client_completed)finally: log.debug(’closing event loop’) event_loop.close()

以上這篇python 使用事件對象asyncio.Event來同步協(xié)程的操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。

標簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 西藏| 都安| 仙游县| 和龙市| 敦化市| 乌拉特前旗| 浦北县| 开远市| 宜良县| 济源市| 文水县| 鄂尔多斯市| 泗阳县| 乐清市| 阆中市| 北安市| 宁南县| 云龙县| 佳木斯市| 贵定县| 祥云县| 托克逊县| 读书| 平遥县| 广河县| 张家港市| 佛坪县| 保山市| 仁寿县| 拜泉县| 方正县| 鄯善县| 治县。| 辽源市| 额敏县| 施甸县| 韩城市| 武川县| 北安市| 四子王旗| 宜章县|