I have to create multi threads that pass a list and a string:
#!/usr/bin/env python3.9
import os
import threading
import time
import asyncio
def func(test, hello):
print(test, hello)
time.sleep(5)
async def newTest(test, hello):
thread = threading.Thread(target=func, args=(test, hello))
print(thread.name, os.getpid())
thread.start()
async def start():
for letter in list_a:
test = f"Test {letter}"
await newTest(test, "hello")
loop.stop()
list_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
loop = asyncio.get_event_loop()
task_start = loop.create_task(start())
loop.run_forever()
output:
Thread-1 43799
Test a hello
Thread-2 43799
Test b hello
Thread-3 43799
Test c hello
Thread-4 43799
Test d hello
Thread-5 43799
Test e hello
Thread-6 43799
Test f hello
Thread-7 43799
Test g hello
I've realized that imap_unordered and ThreadPool doesn't fit my need if I understand correctly: Thread pool will provide benefits for frequent and relatively short operations by reusing threads that have already been created instead of creating new ones - In this case the operation are network I/O type and not so short or numerous.