0

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
ghost239
  • 121
  • 7
  • `imap_unordered` returns an iterator, but because you don't get anything from it, you exit `start` immediately, destroying the `ThreadPool` you just created. But if you put that in a for loop to get the result, you are now doing blocking calls in an async routine, which is not good. Instead, use the async version of the thread pool. – tdelaney Dec 03 '22 at 16:32

0 Answers0