我想运行多个线程,每个线程都有相同的目的,但每个线程使用不同的方法。因此,当其中一个找到数据时,我就不再需要其他的了,我可以杀掉他们。我读到杀死线程并不好,因为它们可能正在使用关键资源做一些事情。所以我的问题是,我怎样才能在不做“坏”事情的情况下实现这种目标?
最佳答案
您可以使用multiprocessing
来做到这一点.
假设我们有两个计算 Pi 值的函数:calculate1()
和 calculate2()
。在这种情况下,calculate2()
速度更快。
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
输出:
calculate1 started
calculate2 started
calculate2 found the result!
Got result: 3.14
关于python - 运行多个线程,直到一个线程在 python 中退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32026028/