运行 多个线程,直到一个线程在 python 中退出

Run multiple threads until one exits in python

我想运行多个线程,每个线程都有相同的目的但每个使用不同的方法。因此,当其中一个找到数据时,我不再需要其他的,我可以杀死它们。我读到杀死线程是不好的,因为它们可能正在使用关键资源做某事。所以我的问题是,如果不做 'bad' 事情,我怎么能实现这种事情?

您可以使用 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