最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2020年05月04日 18:07:23   作者:caimouse  
這篇文章主要介紹了python 使用事件對象asyncio.Event來同步協程的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

事件對象asyncio.Event是基于threading.Event來實現的。

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

例子如下:

import asyncio
import 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: False
coro2 waiting for event
coro1 waiting for event
setting event in callback
coro2 triggered
coro1 triggered
event end state: True

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

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

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

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

在這個類的構造函數里,接收兩個參數messages和future,

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

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

服務器收到數據和標志都回復客戶端,客戶端data_received函數接收數據,eof_received函數接收結束標記。

connection_lost函數收到服務器斷開連接。

這行代碼:

client_completed = asyncio.Future()

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

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

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

import asyncio
import functools
import logging
import 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來同步協程的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • Python3爬蟲中Selenium的用法詳解

    Python3爬蟲中Selenium的用法詳解

    在本篇內容里小編給大家分享了關于Python3爬蟲中Selenium的用法詳解內容,需要的朋友們可以參考下。
    2020-07-07
  • caffe binaryproto 與 npy相互轉換的實例講解

    caffe binaryproto 與 npy相互轉換的實例講解

    今天小編就為大家分享一篇caffe binaryproto 與 npy相互轉換的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • 關于Python 常用獲取元素 Driver 總結

    關于Python 常用獲取元素 Driver 總結

    今天小編就為大家分享一篇關于Python 常用獲取元素 Driver 總結,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-11-11
  • 對Pytorch神經網絡初始化kaiming分布詳解

    對Pytorch神經網絡初始化kaiming分布詳解

    今天小編就為大家分享一篇對Pytorch神經網絡初始化kaiming分布詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • 如何學習Python time模塊

    如何學習Python time模塊

    在本篇文章里小編給大家分享的是關于Python time模塊知識點及用法,需要的朋友們可以學習下。
    2020-06-06
  • Matplotlib繪制子圖的常見幾種方法

    Matplotlib繪制子圖的常見幾種方法

    Matplotlib的可以把很多張圖畫到一個顯示界面,在作對比分析的時候非常有用。本文就介紹了幾種方法,需要的朋友們下面隨著小編來一起學習學習吧
    2021-05-05
  • opencv 圖像禮帽和圖像黑帽的實現

    opencv 圖像禮帽和圖像黑帽的實現

    這篇文章主要介紹了opencv 圖像禮帽和圖像黑帽的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-07-07
  • 在Python的Flask框架下使用sqlalchemy庫的簡單教程

    在Python的Flask框架下使用sqlalchemy庫的簡單教程

    這篇文章主要介紹了在Python的Flask框架下使用sqlalchemy庫的簡單教程,用來簡潔地連接與操作數據庫,需要的朋友可以參考下
    2015-04-04
  • python爬蟲解決驗證碼的思路及示例

    python爬蟲解決驗證碼的思路及示例

    這篇文章主要介紹了python爬蟲解決驗證碼的思路及示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-08-08
  • python的正則表達式和re模塊詳解

    python的正則表達式和re模塊詳解

    這篇文章主要為大家詳細介紹了python的正則表達式和re模塊,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-02-02

最新評論

定州市| 永州市| 芜湖市| 五大连池市| 南开区| 垦利县| 容城县| 石楼县| 开鲁县| 鹤岗市| 庄河市| 铜山县| 乌拉特前旗| 云浮市| 新丰县| 高唐县| 邵武市| 楚雄市| 绵阳市| 平乐县| 泰州市| 南投县| 绥江县| 顺平县| 滨州市| 泸水县| 灯塔市| 隆子县| 大田县| 凤山县| 永寿县| 临猗县| 天长市| 铜陵市| 尼勒克县| 定西市| 永清县| 宣恩县| 沈丘县| 曲靖市| 高陵县|