如何通过多线程tas发出pyqtsignal

2024-04-23 09:44:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过多线程方式发出pyqtsignal。我创建了一个执行计算的函数(例如func)。以及另一个接受该任务并在多个线程中运行的函数(例如function)。在

当我使用父线程时,代码运行得很好。但是,当我使用多个线程时,计算工作得很好,但是没有发出信号。在

我需要使用多线程处理,因为我正在编写的函数执行计算开销很大的任务。在

下面是示例代码(我在这个例子中使用了简单的print函数)

from PyQt5.QtCore import QObject, pyqtSignal,pyqtSlot
import time
from threading import Thread
import sys
import math
import concurrent.futures


class Plot2D(QObject):
    finish=pyqtSignal(float)

    def __init__(self):
        super(Plot2D,self).__init__()

    def Function(self):
        st = time.time()

        # Using parent thread
        # self.func()

        # Using multi-thread 1
        #t=Thread(target=self.func)
        #t.start()
        #t.join()

        # Using multi-thread 2
        with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
           f = executor.submit(self.func)
        en = time.time()
        print(en-st)

    def func(self):
        n=10
        v=(1*100/(n-1))

        for i in range(n):
            print('thread')
            self.finish.emit(v)

    def fprint(self):
        print('works')

obj=Plot2D()
obj.finish.connect(obj.fprint)
obj.Function()

Tags: 函数fromimportselfobjtimedef线程
1条回答
网友
1楼 · 发布于 2024-04-23 09:44:26

您必须清楚以下概念:信号需要一个事件循环才能工作。

考虑到上述情况,解决方案是:

  • 在线程。线程在

您不应该使用join(),因为它会阻塞事件循环所在的主线程,并且由于上述原因,信号将不起作用。在

from PyQt5 import QtCore
from threading import Thread


class Plot2D(QtCore.QObject):
    finished = QtCore.pyqtSignal(float)

    def Function(self):
        Thread(target=self.func).start()

    def func(self):
        n = 10
        v = 1 * 100 / (n - 1)

        for i in range(n):
            print("thread")
            self.finished.emit(v)

    @QtCore.pyqtSlot()
    def fprint(self):
        print("works")


if __name__ == "__main__":
    import sys

    app = QtCore.QCoreApplication(sys.argv)
    obj = Plot2D()
    obj.finished.connect(obj.fprint)
    obj.Function()
    sys.exit(app.exec_())

输出:

^{pr2}$
  • 在同时期货在

不要使用with,因为它会使executor阻塞主线程(而且我们已经知道它会产生什么问题),它还会调用executor.shutdown(wait = False)

^{3}$

输出:

thread
thread
works
thread
works
thread
works
thread
works
thread
thread
works
thread
works
thread
works
thread
works
works
works

相关问题 更多 >