Eloi Canals Pascual
Eloi Canals Pascual

Reputation: 87

Python Multithreading - How to execute a function as soon as the first thread finishes?

I am working with Python threading module to execute the same function in parallel two times, but with different arguments. I want to display the results as soon as one of the thread finishes, and then display the results of the second thread when it finishes. I am trying to do it by putting the results of the function which is being called in a queue and then waiting for the values in the main thread. The code I'm using is the following:

import threading
import queue
import time

q = queue.Queue()
thread1 = threading.Thread(target=some_func, args=(q,0))
thread2 = threading.Thread(target=some_func, args=(q,1))

thread1.start()
thread2.start()

first_result = q.get()
print(first_result)


second_result = q.get()
print(second_result)


def some_func(queue: queue.Queue, val: int):
    time.sleep(val*2 + 5)
    queue.put(val)

Now it is waiting for both threads to finish execution and prints out the result at the same time. Can someone help me?

Thank you!

Upvotes: 0

Views: 481

Answers (1)

JayPeerachai
JayPeerachai

Reputation: 3842

Queue.get() blocks until there is a result available in the queue. This means that the main thread may waits indefinitely until both threads had finished executing and added their results to the queue. However, you can use timeout to confirm that it allows the main thread to check for new results in the queue at regular intervals, without blocking indefinitely.

Try this:

thread1.start()
thread2.start()

# Loop until both threads have finished
while thread1.is_alive() or thread2.is_alive():
    # Check for new results in the queue every 0.1 seconds
    try:
        result = q.get(timeout=0.1)
        print(result)
    except queue.Empty:
        pass

print(f"[{time.asctime()}] Result: {result}"), I used this to confirm that they don't print at the same time.

output:

[Mon Dec 19 22:31:07 2022] Result: 0
[Mon Dec 19 22:31:09 2022] Result: 1

Upvotes: 2

Related Questions