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

标签 python multithreading kill

我想运行多个线程,每个线程都有相同的目的,但每个线程使用不同的方法。因此,当其中一个找到数据时,我就不再需要其他的了,我可以杀掉他们。我读到杀死线程并不好,因为它们可能正在使用关键资源做一些事情。所以我的问题是,我怎样才能在不做“坏”事情的情况下实现这种目标?

最佳答案

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

相关文章:

python - 具有动态路径的 send_from_directory

java - 显示 Java 中与 2 个线程同步的用法

java - 如何停止或退出 "Runnable"

c - 最后一个 fork 的 child 不会死

python - python中函数内的函数

python - 我的自定义 Django 应用程序代码在哪里?

java - 向多个客户端广播消息时如何排除或跳过发送者(多线程java套接字)

bash:while 循环内的计数器(kill 和 kill -9)

android - 如何杀死我自己的 Activity - 艰难的方式

python - Pandas 将字符串转换为数据框中多列的 float