Python/PySide:如何销毁终止的线程对象?

Python/PySide:如何销毁终止的线程对象?,python,multithreading,pyqt,multiprocessing,pyside,Python,Multithreading,Pyqt,Multiprocessing,Pyside,我想实现一个按钮来停止一个进程的线程,它可以正常工作,但不能像预期的那样:我不能删除线程对象。(编辑:对线程对象的引用似乎已被删除,但删除线程对象不会自动断开信号,我仍然可以通过信号访问它。) 我有一个带有类thread_worker的模块和一个作为进程运行的复杂处理函数: from PySide.QtCore import * from PySide.QtGui import * import multiprocessing as mp import time # this function

我想实现一个按钮来停止一个进程的线程,它可以正常工作,但不能像预期的那样:我不能删除线程对象。(编辑:对线程对象的引用似乎已被删除,但删除线程对象不会自动断开信号,我仍然可以通过信号访问它。)

我有一个带有类thread_worker的模块和一个作为进程运行的复杂处理函数:

from PySide.QtCore import *
from PySide.QtGui import *
import multiprocessing as mp
import time

# this function runs as a process
def complex_processing(queue):
    # do something
    ...

class thread_worker(QThread):
    message_signal = Signal(str)
    stop_thread_signal = Signal()

    def __init__(self, prozessID, sleepTime, parent=None):
        super(ThreadProzessWorker, self).__init__(parent)
        self.queue = mp.Queue()
        self.process = mp.Process(target=complex_processing, args=(self.queue,))
        self.timeStamp = int(time.time())

    def run(self):
        self.process.start()
        self.process.join()

    @Slot()
    def stop_process_and_thread(self):
        if self.isRunning():
            self.message_signal.emit("Thread %d is running!" % self.timeStamp)
            if self.process.is_alive():
                self.process.terminate()
                self.process.join()      
            self.stop_thread_signal.emit()   
            #self.terminate() # does it works at this place?       
        else:
            self.message_signal.emit("Thread %d is not running!" % self.timeStamp)
我的应用程序中有两个按钮用于创建/运行和终止线程对象

...
...
# Buttons
self.button_start_thread = QPushButton("Start Thread")
self.button_start_thread.clicked.connect(self.start_thread)
self.button_stop_thread = QPushButton("Stop Thread")
...
...
@Slot()
def start_thread(self):
    self.new_thread = thread_worker(self)
    self.button_stop_thread.clicked.connect(self.new_thread.stop_process_and_thread)
    self.new_thread.stop_thread_signal.connect(self.stop_thread)
    self.new_thread.message_signal.connect(self.print_message)
....
....
@Slot()
def stop_thread(self):
    self.new_thread.terminate()
    #self.button_stop_thread.disconnect(self.new_thread)
    del(self.new_thread)

@Slot(str)
def print_message(self, message):
    print(message)
...
...
如果我启动并停止第一个线程-它工作正常并终止,但如果我再次单击“停止”按钮,则输出为:

Thread 1422117088 is not running!
Thread 1422117088 is not running!  # not expected, the thread object is deleted!
Thread 1422117211 is running!      # expected
Thread 1422117088 is not running!   # not expected, the thread object is deleted!
Thread 1422117211 is not running!   # not expected, the thread object is deleted!
Thread 1422117471 is running!       # expected
我不明白:对象
self.new\u线程
是否被
del(self.new\u线程)
删除?如果此对象已被删除,我如何访问它?如果我再次启动并停止一个新线程,则输出为:

Thread 1422117088 is not running!
Thread 1422117088 is not running!  # not expected, the thread object is deleted!
Thread 1422117211 is running!      # expected
Thread 1422117088 is not running!   # not expected, the thread object is deleted!
Thread 1422117211 is not running!   # not expected, the thread object is deleted!
Thread 1422117471 is running!       # expected
现在我再做一次(启动和停止),输出是:

Thread 1422117088 is not running!
Thread 1422117088 is not running!  # not expected, the thread object is deleted!
Thread 1422117211 is running!      # expected
Thread 1422117088 is not running!   # not expected, the thread object is deleted!
Thread 1422117211 is not running!   # not expected, the thread object is deleted!
Thread 1422117471 is running!       # expected
等等

第一个问题: 我不明白为什么老线程没有被删除?为什么我可以访问它们?我认为这不好:如果后台有太多线程(不是删除的对象),我的应用程序会在某个时候崩溃

第二个问题: 我不明白如果我删除对象
self.new\u thread
,为什么信号没有断开?我不想手动断开信号:如果我有很多信号,我会忘记断开一些信号

第三个问题: 我选择这种方式来用一个进程停止一个线程。还有其他更好的方法吗

更新:

线程对象似乎已被销毁:

del(self.new_thread)
print(self.new_thread)
Output: AttributeError: 'MainWindow' object has no attribute 'new_thread'

但我的信号没有断开!?描述为:“当所涉及的任何一个对象被破坏时,信号插槽连接被删除。”它在我的代码中不起作用。

发生这种情况可能是因为您的进程不包含任何内容,并且在启动后完成。因此

def stop_process_and_thread(self):
    if self.isRunning():
        ...
        if self.process.is_alive():
            self.process.terminate()
            self.process.join()      
            self.stop_thread_signal.emit()   
            #self.terminate() # does it works at this place?  
在if self.process.is_alive()之后,永远不会到达。因此,停止线程信号永远不会发出,因此线程既不会终止也不会删除

将测试复杂度_处理函数更改为

def complex_processing(queue):
# do something
  while(True):
    print "in process"
    time.sleep(0.2)
现在,为了达到您想要的效果,您应该将线程存储在一个列表中,这样开始线程就应该

def start_thread(self):
    n = len(self.new_thread)
    self.new_thread.append(thread_worker(self))
    self.new_thread[-1].setTerminationEnabled(True)
    self.new_thread[-1].start()
    if n>0:
        self.button_stop_thread.clicked.disconnect()
    self.button_stop_thread.clicked.connect(self.new_thread[-1].stop_process_and_thread)
    print self.new_thread
    self.new_thread[-1].stop_thread_signal.connect(self.stop_thread)
    self.new_thread[-1].message_signal.connect(self.print_message)
请注意,在设置与列表中最后一个线程(新添加的线程)的连接之前,必须首先断开button clicked()信号与所有插槽的连接。这是因为如果启动多个线程,那么clicked()信号将连接到所有线程的插槽。因此,stop_进程和stop_线程以及stop_线程的调用次数将与具有不可预测序列的运行线程数相同。 通过断开信号,只有最后启动的线程才会终止并从列表中删除。另外,请确保已设置setTerminationEnabled

但是,在这之后,您必须重新连接按钮单击信号,因此您还必须将停止线程方法更改为

def stop_thread(self):
    del(self.new_thread[-1])
    if self.new_thread: # if no threads left, then no need ro reconnect signal
         self.button_stop_thread.clicked.connect(self.new_thread[-1].stop_process_and_thread)
    print self.new_thread 
至于终止,这可以在停止进程和线程方法中完成。(这是您注释掉的行,请在发出信号之前放置它,以防万一)

现在,您的程序应按预期运行

对于您的第一个问题,我不确定线程是否被删除,但现在可以确定它们是否被终止。在以前的代码中,由于将所有变量都赋给一个变量,而其中一些变量仍处于活动状态,因此您可能会丢失引用。这也回答了你的第二个问题

至于第三种,qt文档中不建议以这种方式终止线程。你应该在那里搜索更好更安全的方法,我也不太确定你是否使用了多处理,但我不能告诉你更多,因为我没有经常使用这个模块


我相信你应该改变编程的策略。最好在进程内使用线程,而不是像您那样在线程内使用进程。您是对的,您的问题是,您的对象没有被删除。您只删除引用
self.new\u线程
。问题出在这一行:

self.new_thread = thread_worker(self)
这是因为线程的父级
self
处于活动状态。只要父线程保持活动状态,对象
self.new\u线程就不会被销毁。试着这样做:

self.threadParent = QObject()
self.new_thread = thread_worker(self.threadParent)
import time
from threading import Thread

class myClass(object):
    def __init__(self):
        self._is_exiting = False

        class dummpyClass(object):
            pass
        newSelf = dummpyClass()
        newSelf.__dict__ = self.__dict__

        self._worker_thread = Thread(target=self._worker, args=(newSelf,), daemon=True)

    @classmethod
    def _worker(cls, self):
        i = 0
        while not self._is_exiting:
            print('Loop #{}'.format(i))
            i += 1
            time.sleep(3)
    def __del__(self):
        self._is_exiting = True
        self._worker_thread.join()
现在还删除了父级
self.threadParent

self.new_thread.terminate()
del(self.new_thread)
del(self.threadParent)
你的信号现在应该断开了

您不需要以下行,因为在发出信号“停止线程”信号后,对象“self.new\u thread”已被删除:

#self.terminate() # does it works at this place?

我以前处理过这个问题,解决的方法如下:

self.threadParent = QObject()
self.new_thread = thread_worker(self.threadParent)
import time
from threading import Thread

class myClass(object):
    def __init__(self):
        self._is_exiting = False

        class dummpyClass(object):
            pass
        newSelf = dummpyClass()
        newSelf.__dict__ = self.__dict__

        self._worker_thread = Thread(target=self._worker, args=(newSelf,), daemon=True)

    @classmethod
    def _worker(cls, self):
        i = 0
        while not self._is_exiting:
            print('Loop #{}'.format(i))
            i += 1
            time.sleep(3)
    def __del__(self):
        self._is_exiting = True
        self._worker_thread.join()
dummpyClass的使用允许worker访问我们的主类的所有属性,但它实际上并不指向它。因此,当我们删除我们的主类时,它有可能被完全取消引用

test = myClass()
test._worker_thread.start()
请注意,我们的工作人员开始打印输出

del test
工作线程已停止

解决这个问题的一个更复杂的方法是首先定义一个基类(称为myClass_base),该基类存储所有数据和所需的方法,但不支持线程。然后在新类中添加线程支持

import time
from threading import Thread
class myClass_base(object):
    def __init__(self, specialValue):
        self.value = specialValue
    def myFun(self, x):
        return self.value + x

class myClass(myClass_base):
    def __init__(self, *args, **kwargs):

        super(myClass, self).__init__(*args, **kwargs)

        newSelf = myClass_base.__new__(myClass_base)
        newSelf.__dict__ = self.__dict__

        self._is_exiting = False

        self.work_to_do = []

        self._worker_thread = Thread(target=self._worker, args=(newSelf,), daemon=True)

    @classmethod
    def _worker(cls, self):
        i = 0
        while not self._is_exiting:
            if len(self.work_to_do) > 0:
                x = self.work_to_do.pop()
                print('Processing {}.  Result = {}'.format(x, self.myFun(x)))
            else:
                print('Loop #{}, no work to do!'.format(i))
            i += 1
            time.sleep(2)

    def __del__(self):
        self._is_exiting = True
        self._worker_thread.join()
要启动此类,请执行以下操作:

test = myClass(3)
test.work_to_do+=[1,2,3,4]
test._worker_thread.start()
请注意,结果开始打印出来。删除操作与以前相同。执行

del test

线程将正确退出。

谢谢您的回答!我已经更新了问题中的代码:(1)
complex_processing()
do something,这是一个最小的例子;(2)
self.stop\u thread\u signal.emit()
不在
if…
下。我在代码中添加了
setTerminationEnabled(True)
,但它不起作用。我也可以在没有
setTerminationEnabled(True)
的情况下终止线程,这不是问题,我无法删除线程对象-tha