1
我想运行多个线程,每个线程都有相同的目的,但每个使用不同的方法。因此,当他们中的一个人发现数据时,我不再需要其他人,我可以杀死他们。我已经读过,杀死线程并不好,因为他们可能会用关键资源做某件事。所以我的问题是,如何在不做坏事情的情况下实现这种事情?运行多个线程,直到一个退出python
我想运行多个线程,每个线程都有相同的目的,但每个使用不同的方法。因此,当他们中的一个人发现数据时,我不再需要其他人,我可以杀死他们。我已经读过,杀死线程并不好,因为他们可能会用关键资源做某件事。所以我的问题是,如何在不做坏事情的情况下实现这种事情?运行多个线程,直到一个退出python
您可以使用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
太好了!正是我需要的,谢谢。 – pystudent
没有队列可以做到这一点吗?因为我更喜欢,如果可能的话,在不改变方法的情况下(添加参数和result_queue.put ...) – pystudent
@pystudent我不确定。但是,如果您不想修改原始函数,则可以考虑制作包装函数。 – Sait