I have a requirement for a project to use several hundred threads and each thread should run an asynchronous function. At the end, I need to collect results from all the threads. I have following example but it works synchronously.
import asyncio
import concurrent.futures
async def count():
print("One")
# here I need to use an asynchronous function
await asyncio.sleep(2)
print("Two")
return "some result"
async def main():
futures = []
with concurrent.futures.ThreadPoolExecutor() as executor:
for _ in range(5):
future = executor.submit(count)
futures.append(future)
results = [await f.result() for f in concurrent.futures.as_completed(futures)]
print(results)
if __name__ == "__main__":
asyncio.run(main())
Code above outputs:
One
Two
One
Two
One
Two
One
Two
One
Two
['some result', 'some result', 'some result', 'some result', 'some result']
Expected output:
One
One
One
One
One
Two
Two
Two
Two
Two
['some result', 'some result', 'some result', 'some result', 'some result']