日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python协程asyncio 应用_Python-如何使用asyncio同时运行多个协程?

發(fā)布時間:2025/3/15 python 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python协程asyncio 应用_Python-如何使用asyncio同时运行多个协程? 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

TL;DR使用^{}同時運行多個協(xié)程。Maybe this scenario requires a framework based on events/callbacks rather than one based on coroutines? Tornado?

不,你不需要其他框架。異步應(yīng)用程序與同步應(yīng)用程序的整體思想是,在等待結(jié)果時,它不會阻塞。不管它是如何實現(xiàn)的,使用協(xié)程或回調(diào)。I mean, because connection_handler is constantly waiting for incoming messages, the server can only take action after it has received a message from the client, right? What am I missing here?

在同步應(yīng)用程序中,您將編寫類似msg = websocket.recv()的內(nèi)容,這將阻塞整個應(yīng)用程序,直到您收到消息為止(如您所述)。但在異步應(yīng)用程序中則完全不同。

當(dāng)你做msg = yield from websocket.recv()時,你會說:暫停connection_handler()的執(zhí)行,直到websocket.recv()產(chǎn)生某些結(jié)果。在coroutine中使用yield from將控制返回到事件循環(huán),以便在等待websocket.recv()的結(jié)果時可以執(zhí)行其他一些代碼。請參閱documentation以更好地了解協(xié)同工作的工作原理。Let's say we – additionally – wanted to send a message to the client whenever some event happens. For simplicity, let's send a message periodically every 60 seconds. How would we do that?

在對starting event loop執(zhí)行阻塞調(diào)用之前,可以使用^{}運行任意數(shù)量的協(xié)程。import asyncio

import websockets

# here we'll store all active connections to use for sending periodic messages

connections = []

@asyncio.coroutine

def connection_handler(connection, path):

connections.append(connection) # add connection to pool

while True:

msg = yield from connection.recv()

if msg is None: # connection lost

connections.remove(connection) # remove connection from pool, when client disconnects

break

else:

print('< {}'.format(msg))

yield from connection.send(msg)

print('> {}'.format(msg))

@asyncio.coroutine

def send_periodically():

while True:

yield from asyncio.sleep(5) # switch to other code and continue execution in 5 seconds

for connection in connections:

print('> Periodic event happened.')

yield from connection.send('Periodic event happened.') # send message to each connected client

start_server = websockets.serve(connection_handler, 'localhost', 8000)

asyncio.get_event_loop().run_until_complete(start_server)

asyncio.async(send_periodically()) # before blocking call we schedule our coroutine for sending periodic messages

asyncio.get_event_loop().run_forever()

下面是一個示例客戶機實現(xiàn)。它要求您輸入名稱,從echo服務(wù)器接收它,等待來自服務(wù)器的另外兩條消息(這是我們的周期性消息)并關(guān)閉連接。import asyncio

import websockets

@asyncio.coroutine

def hello():

connection = yield from websockets.connect('ws://localhost:8000/')

name = input("What's your name? ")

yield from connection.send(name)

print("> {}".format(name))

for _ in range(3):

msg = yield from connection.recv()

print("< {}".format(msg))

yield from connection.close()

asyncio.get_event_loop().run_until_complete(hello())

要點:在Python 3.4.4中,asyncio.async()被重命名為^{}。

調(diào)度delayed calls有一些特殊的方法,但它們不適用于協(xié)程。

總結(jié)

以上是生活随笔為你收集整理的python协程asyncio 应用_Python-如何使用asyncio同时运行多个协程?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。