我试图同时为列表中的单个客户端运行2个任务,但它没有按预期工作 - 任务仍然同步运行(请参阅Output
)。你能帮我理解我的代码有什么问题吗?谢谢。
#!/usr/bin/env python3
import asyncio
async def do_b(client):
print('{}: doing b...'.format(client))
await asyncio.sleep(1)
print('{}: b is done!'.format(client))
async def do_a(client):
print('{}: doing a...'.format(client))
await asyncio.sleep(1)
print('{}: a is done!'.format(client))
async def loop_a():
clients = ['CLIENT-1', 'CLIENT-2', 'CLIENT-3', 'CLIENT-4', 'CLIENT-5']
for client in clients:
task1 = asyncio.ensure_future(do_a(client))
task2 = asyncio.ensure_future(do_b(client))
await asyncio.gather(task1, task2)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(loop_a())
loop.close()
CLIENT-1: doing a...
CLIENT-1: doing b...
CLIENT-1: a is done!
CLIENT-1: b is done!
CLIENT-2: doing a...
CLIENT-2: doing b...
CLIENT-2: a is done!
CLIENT-2: b is done!
CLIENT-3: doing a...
CLIENT-3: doing b...
CLIENT-3: a is done!
CLIENT-3: b is done!
CLIENT-4: doing a...
CLIENT-4: doing b...
CLIENT-4: a is done!
CLIENT-4: b is done!
CLIENT-5: doing a...
CLIENT-5: doing b...
CLIENT-5: a is done!
CLIENT-5: b is done!
编辑:
另一个问题。如何让它像这样执行,不遵循列表中的顺序?因为目前,CLIENT-1
被CLIENT-2
阻止,与其他客户端一样,我试图避免这种情况。这可能吗?
CLIENT-1: doing a...
CLIENT-2: doing a...
CLIENT-1: doing b...
CLIENT-3: doing a...
CLIENT-1: a is done!
CLIENT-1: b is done!
CLIENT-2: a is done!
CLIENT-3: a is done!
CLIENT-2: doing b...
CLIENT-2: b is done!
CLIENT-3: doing b...
CLIENT-3: b is done!
答案 0 :(得分:1)
首先,两个任务并非同步运行,因为您可以看到doing b...
一直显示在doing a...
和a is done!
之间的事实
每对任务在下一个客户端启动之前完成,但那是因为你明确要求这样做。如果您不想await
每对,只需......每对await
。例如:
futs = []
for client in clients:
futs.append(asyncio.ensure_future(do_a(client)))
futs.append(asyncio.ensure_future(do_b(client)))
await asyncio.gather(*futs)
答案 1 :(得分:0)
a
和b
同时运行,输出结果显示。客户端1,2,3,4和5按顺序运行,因为它们之间存在await asyncio.gather
。
您可以将所有任务合并到一个列表中,以使它们同时运行:
async def loop_a():
clients = ['CLIENT-1', 'CLIENT-2', 'CLIENT-3', 'CLIENT-4', 'CLIENT-5']
tasks = []
for client in clients:
tasks.append(asyncio.ensure_future(do_a(client)))
tasks.append(asyncio.ensure_future(do_b(client)))
await asyncio.gather(*tasks)
现在打印:
CLIENT-1: doing a...
CLIENT-1: doing b...
CLIENT-2: doing a...
CLIENT-2: doing b...
CLIENT-3: doing a...
CLIENT-3: doing b...
CLIENT-4: doing a...
CLIENT-4: doing b...
CLIENT-5: doing a...
CLIENT-5: doing b...
CLIENT-1: a is done!
CLIENT-2: a is done!
CLIENT-3: b is done!
CLIENT-1: b is done!
CLIENT-3: a is done!
CLIENT-2: b is done!
CLIENT-4: a is done!
CLIENT-5: b is done!
CLIENT-4: b is done!
CLIENT-5: a is done!