Python 在长时间运行的任务中终止QThread和multiprocessing.pool进程

Python 在长时间运行的任务中终止QThread和multiprocessing.pool进程,python,python-2.7,multiprocessing,pyqt4,qthread,Python,Python 2.7,Multiprocessing,Pyqt4,Qthread,PyQt4和Python 2.7 我有一个GUI应用程序,它管理相当大的数据集的处理。找到这些数据集/文件,将其分组为一组要一起处理的文件,然后进行转换和处理。沿途的每一步都在代码中进行了分解。我们的想法是能够分别停止和启动这些“步骤” 我已经让开始部分工作得很好了,基本上是使用队列在转换/处理步骤的整个过程中提供信息。我现在的问题是让他们停止 我有一个很小的例子来说明我正在尝试做什么。但本质上,我启动了一个QThread,它接受一组相关项,QThread然后通过multiprocessing.

PyQt4和Python 2.7

我有一个GUI应用程序,它管理相当大的数据集的处理。找到这些数据集/文件,将其分组为一组要一起处理的文件,然后进行转换和处理。沿途的每一步都在代码中进行了分解。我们的想法是能够分别停止和启动这些“步骤”

我已经让开始部分工作得很好了,基本上是使用队列在转换/处理步骤的整个过程中提供信息。我现在的问题是让他们停止

我有一个很小的例子来说明我正在尝试做什么。但本质上,我启动了一个
QThread
,它接受一组相关项,
QThread
然后通过
multiprocessing.pool.map
命令worker,这是一个非常长的运行进程。运行时间很长,这意味着处理可能需要20分钟……但我希望能够立即停止池中的所有进程。我在这里使用了while循环,在完整的代码中,它是使用
子进程调用外部exe

一旦长时间运行的任务在worker内部运行,我似乎无法找到一种方法来强制杀死它……尽管
PyCharm
的“停止”按钮能够正确地杀死它们。我不在这里共享任何变量,如果当前正在“处理”的项目损坏,我不在乎,因为它们将在下次运行时被替换(因为它没有完全完成任务)

我怎样才能阻止我的工人

from multiprocessing import Queue, Pool
from PyQt4.QtCore import *
import time
from itertools import repeat


#Worker that actually does the long work task
#Just printing in a while loop here
def worker(ID):
    while 1:
        print "Hello World from ", ID
        time.sleep(1)
    else:
        return

#QThread which manages the workers
#MyThread gets collection of tasks to perform and then sends work out to pool of workers
#Planning for at least 3 of these to be running simultaneously in full blown script
class MyThread(QThread):
    def __init__(self, inqueue, outqueue, id):
        super(MyThread, self).__init__()
        self.inqueue = inqueue
        self.outqueue = outqueue
        self.ID = id
        print 'initializedL: ', self.ID

    def run(self):

        while 1:
            print "Waiting"
            obj = self.inqueue.get(block=True)
            self.pool = Pool(processes=6)
            self.res = self.pool.map(worker, zip(obj, repeat(self.ID)))
            self.pool.close()
            self.pool.join()

    def stop(self):
        self.terminate()

if __name__ == "__main__":

    inqueue = Queue()
    outqueue = Queue()

    #start a new QThread which immediately waits for work to be assigned to it
    t = MyThread(inqueue, outqueue, 1)
    t.start()

    time.sleep(2)

    #Provide the QThread with a collection of items for the worker to process
    inqueue.put([1, 2, 3, 4, 5, 6, 7, 8])

    time.sleep(5)

    #At some point, I want to be able to completely dead stop all processes and threads
    #associated with MyThread...again will be 3 MyThreads in full version
    t.stop()

    db=2
    #SET DEBUG BREAKPOINT HERE TO SEE LOOP CONTINUE TO RUN

stop
方法中,添加对
self.pool.terminate的调用。根据

文档中,
Pool.terminate
函数会立即停止工作进程。

谢谢@mguijarr,我应该已经找到了。顺便说一句,我的实际工作人员是长的
子流程。Popen
调用,我在等待返回
池()时插入了一个队列和循环。
我检查队列中是否有毒丸。这种情况非常复杂,但是
pool.terminate()
绝对是我需要的第一步!