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)?