pystudent
pystudent

Reputation: 571

Run multiple threads until one exits in python

I would like to run multiple threads, each of them has the same purpose but each uses a different method. Therefore, when one of them finds the data, I no longer need the other ones and I can just kill them. I've read that it isn't good to kill threads because they might be doing something with a crucial resource. So my question is, how can I achieve this kind of thing without doing 'bad' things?

Upvotes: 1

Views: 68

Answers (1)

Sait
Sait

Reputation: 19815

You can do it using multiprocessing.

Let's say we have two functions who calculate the value of Pi, calculate1() and calculate2(). In this case calculate2() is faster.

import multiprocessing
import time

def calculate1(result_queue):
    print "calculate1 started"
    time.sleep(10)
    result = 3.14
    result_queue.put(result)
    print "calculate1 found the result!"

def calculate2(result_queue):
    print "calculate2 started"
    time.sleep(2)
    result = 3.14
    result_queue.put(result)
    print "calculate2 found the result!"

result_queue = multiprocessing.Queue()

process1 = multiprocessing.Process(target=calculate1, args=[result_queue])
process2 = multiprocessing.Process(target=calculate2, args=[result_queue])

process1.start()
process2.start()

print "Calculating the result with 2 threads."

result = result_queue.get() # waits until any of the proccess have `.put()` a result

for process in [process1, process2]: # then kill them all off
    process.terminate()

print "Got result:", result

This outputs:

calculate1 started
calculate2 started
calculate2 found the result!
Got result: 3.14

Upvotes: 2

Related Questions