1

The following code starts a few threads and prints the result after they are all done:

import threading

results = [None] * 5
threads = [None] * 5

def worker(i):
    results[i] = i

for i in range(5):
    threads[i] = threading.Thread(target=worker, args=(i,))
    threads[i].start()

# here I would like to use the results of the threads which are finished
# while others still run

for i in range(5):
    threads[i].join()

# here I have the results but only when all threads are done
print(results)

As mentioned in the code, I would like to use the results of the threads which are finished while others are still running. What is the correct way to do that?

Should I simply start a new thread which would have a while True: loop and continuously check for a new entry in results or is there a buil-in mechanism for such operations (as part of the threading.Thread call which would point to a callback when the thread is done)?

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • `from multiprocessing.pool import ThreadPool` and you can take it from there. – cs95 Aug 14 '17 at 10:17
  • Might you enumerate upon that? – cs95 Aug 14 '17 at 10:19
  • 'https://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python' may be your answer is here – Kallz Aug 14 '17 at 10:20
  • @cᴏʟᴅsᴘᴇᴇᴅ: thanks, I will try that way. I was hoping that there would be a direct callback mechanism (which I did not find in the docs) – WoJ Aug 14 '17 at 10:20
  • @Kallz: I know how to get the result of a thread (my code is adapted from the second answer to the link you point to). As mentioned before, I was looking for a callback mechanism, if such one exists. – WoJ Aug 14 '17 at 10:22
  • use "isAlive()" method for check thread is running or completed ,first you want to use result of completed result so check result which 'isAlive()' is false and in second condition you want to check result when all thread completed so check result when 'isAlive()' for all thread is false – Kallz Aug 14 '17 at 10:36

1 Answers1

1

Since you're using Python 3, concurrent.futures is a better fit than threading:

import concurrent.futures

results = [None] * 5

def worker(i):
    results[i] = i

with concurrent.futures.ThreadPoolExecutor(5) as pool:
    futmap = {pool.submit(worker, i): i for i in range(len(results))}
    for fut in concurrent.futures.as_completed(futmap):
        print("doing more stuff with", futmap[fut])
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • *The concurrent.futures module provides a high-level interface for asynchronously executing callables* - excellent, this is exactly what I was looking for, thank you! – WoJ Aug 14 '17 at 12:13