循环内调用Python异步函数

问题描述 投票:0回答:2

我有一个服务器和客户端,多个客户端将连接到多个服务器并执行某些操作。我想让客户端与服务器异步连接。

clients = [1,2,3]
for c in clients:
  connect_to_server()

现在上面的代码连接到服务器,但等待第一次迭代执行,然后等待第二次迭代。 如何使其异步函数调用 connect_to_server() 方法,以便第二次迭代不会等待第一次执行? 哪个函数必须是异步的 connect_to_server 或 for 循环函数,哪个函数必须等待?


def connect_to_server(client_id):
    print(client_id)
    time.sleep(3)


async def main():
    clients = [1, 2, 3, 4]
    for client in clients:
       await connect_to_server(client)

asyncio.run(main())
python python-asyncio
2个回答
1
投票

在这里将您想要异步的代码包装在异步函数中,

import asyncio

async def main():

    clients = [1,2,3]

    for c in clients:
        await connect_to_server()

asyncio.run(main())

说明:这里 asyncio 调用异步“MAIN”函数,并且函数中的“AWAIT”使进程继续到下一次迭代,而无需等待 connect_to_server() 函数完成!


0
投票

您的代码将至少运行运行同步代码所需的时间。下面的代码说明了这一点:

import asyncio
import time

async def connect_to_server(client_id):
    print(client_id)
    print(f'sleep for client_id {client_id}')
    time.sleep(1)
    print(f'async sleep for client_id {client_id}')
    await asyncio.sleep(1)
    print(f'done for client_id {client_id}')

async def main():
    clients = range(10)
    
    # Launch all of the coroutines in parallel
    coroutines = [connect_to_server(client) for client in clients]
    
    # Wait for all corountines to complete
    await asyncio.gather(*coroutines)

start = time.time()
asyncio.run(main())
print(f'Time elapsed: {time.time() - start} seconds')

上面的代码需要不少于11秒才能完成。

当心!以下代码循环调用

await connect_to_server

import asyncio
import time

async def connect_to_server(client_id):
    print(client_id)
    print(f'sleep for client_id {client_id}')
    time.sleep(1)
    print(f'async sleep for client_id {client_id}')
    await asyncio.sleep(1)
    print(f'done for client_id {client_id}')

async def main():
    clients = range(10)
    
    # Launch all of the coroutines in parallel
    for client in clients:
        await connect_to_server(client)
    
start = time.time()
asyncio.run(main())
print(f'Time elapsed: {time.time() - start} seconds')

上面的代码需要不少于20秒才能完成。

© www.soinside.com 2019 - 2024. All rights reserved.