【发布时间】:2015-03-23 13:15:04
【问题描述】:
我想实现一个按钮来停止带有进程的线程,它可以工作但没有按预期工作:我无法删除线程对象。 (编辑:似乎删除了对线程对象的引用,但是通过删除线程对象并不会自动断开信号,我可以通过信号访问它。)
我有一个带有类 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!
我不明白:self.new_thread 对象是否被del(self.new_thread) 删除?如果它被删除,我如何访问这个对象?如果我再次启动和停止一个新线程,输出是:
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_thread,为什么信号没有断开?我不想手动断开信号:如果我有很多信号,我可能会忘记断开一些信号。
第三个问题: 我选择这种方式来停止一个进程的线程。还有其他更好的方法吗?
更新:
线程对象似乎已被破坏:
del(self.new_thread)
print(self.new_thread)
Output: AttributeError: 'MainWindow' object has no attribute 'new_thread'
但是我的信号没有断开!? Here 被描述为:“当涉及的任何一个对象被破坏时,信号槽连接被删除。”它在我的代码中不起作用。
【问题讨论】:
-
最后一枪...删除 print(self.new_thread),或将其包含在 try-except 子句中
-
我现在的代码中没有
print(self.new_thread),那只是为了检查对象是否被删除。我们看到,引用self.new_thread被删除,但对象没有被删除。
标签: python multithreading pyqt multiprocessing pyside