Here is a simple example of using asyncio
to print out numbers from 0 to 9.
Problem: Sometimes the code prints out the numbers from 0 to 7, then prints 9, then 8. Especially when you set ThreadPoolExecutor
to a smaller number like 4 or 5.
0
1
2
3
4
5
6
7
9
8
How do you get it to always print in sequence from 0 to 9? Why did it not print in sequence?
0
1
2
3
4
5
6
7
8
9
Code
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))