在长时间运行的任务中杀死QThread和multiprocessing.pool进程

时间:2014-01-12 17:33:50

标签: python python-2.7 multiprocessing pyqt4 qthread

PyQt4和Python 2.7

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

我已经让起始部分工作得非常好,基本上使用队列来提供转换/处理步骤的信息。我现在遇到的问题是让他们停下来......

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

一旦长时间运行的任务在工作人员内部运行,我似乎无法找到强行杀死它的方法....尽管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

1 个答案:

答案 0 :(得分:1)

stop方法中,添加对self.pool.terminate的通话。根据 文档,Pool.terminate函数立即停止工作进程。