【发布时间】:2026-02-06 00:40:01
【问题描述】:
这是一个使用asyncio 打印从0 到9 的数字的简单示例。
问题:有时代码会打印出从 0 到 7 的数字,然后打印 9,然后是 8。尤其是当您将 ThreadPoolExecutor 设置为较小的数字(例如 4 或 5)时。
0
1
2
3
4
5
6
7
9
8
你如何让它总是按从 0 到 9 的顺序打印?为什么没有按顺序打印?
0
1
2
3
4
5
6
7
8
9
代码
import asyncio
from concurrent.futures import ThreadPoolExecutor
async def printThreaded(THREAD_POOL, length):
loop = asyncio.get_event_loop()
futures = []
for i in range(length):
futures.append(loop.run_in_executor(THREAD_POOL, echo, i))
await asyncio.wait(futures)
def echo(i):
print(i)
THREAD_POOL = ThreadPoolExecutor(16)
with THREAD_POOL:
loop = asyncio.get_event_loop()
length = 10
loop.run_until_complete(printThreaded(THREAD_POOL, length))
【问题讨论】:
标签: python multithreading python-3.x python-multithreading python-asyncio