gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:38:33 24 4
gpt4 key购买 nike

PyQt4 和 Python 2.7

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

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

我有一个非常小的例子来说明我正在尝试做的事情。但本质上,我启动了 QThread它接受一组相关的项目,QThread然后通过multiprocessing.pool.map命令worker,这是一个非常长时间运行的进程。运行时间非常长,意味着处理可能需要 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

最佳答案

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

关于python - 在长时间运行的任务中终止 QThread 和 multiprocessing.pool 进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21077924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com