Python 使用 QThread 和线程模块的多线程

Python Multithreading with QThread and Threading Modules

我尝试在程序中启动一个 Qthread 和另一个线程。代码如下所示。 Qthread 必须显示图形。 Qthread 单独使用时工作正常,但当我尝试 运行 一个线程或多个 Qthread 时,它没有显示任何内容。

我的设置:ubuntu 16.04.1 LTS,python 2.7.12

模块:pyqtgraph、时间、numpy、sys、线程

Q线程:plotthread.py

from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import numpy as np
import time
import sys
class guiThread(QtCore.QThread):
    def __init__(self):
        QtCore.QThread.__init__(self)
        self.status=True
        self.range=100
        self.app = QtGui.QApplication(sys.argv)
        self.app.aboutToQuit.connect(self.stop)
        self.win = pg.GraphicsWindow(title="Example")
        self.win.resize(500,400)
        pg.setConfigOptions(antialias=True)
        self.px = self.win.addPlot(title="X plot")
        self.ckx = self.px.plot(pen='y')
        self.cdx = self.px.plot(pen='r')
        self.px.setXRange(0, self.range)
        self.px.setYRange(-180, 180)
        self.px.showGrid(x=True, y=True)
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updateplot)
        self.timer.start(0.001)
        self.kx=np.zeros(self.range)
        self.dx=np.zeros(self.range)

    def updateplot(self):
        self.ckx.setData(self.kx)
        self.cdx.setData(self.dx)

    def append(self,sin):
        self.kx=np.roll(self.kx,-1)
        self.kx[-1]=sin[0]
        self.dx=np.roll(self.dx,-1)
        self.dx[-1]=int(sin[1])
    def stop(self):
        print "Exit" #exit when window closed
        self.status=False
        sys.exit()
    def run(self):
        print "run" #Qthread run
        while self.status:
            sin=np.random.randint(-180,180,2) 
            self.append(sin) #append random number for plot
            time.sleep(0.01)

Python线程:ptiming.py

import  time
import threading

class timeThread (threading.Thread):
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.name=name
        self.t=time.time()
        self.elapsed=0
    def run(self):
        print "thread start"
        while (1):
            self.elapsed=time.time()-self.t
            print self.name, self.elapsed

主要:main.py

import ptiming
import plotthread
t1=plotthread.guiThread()
t1.start()
t2=ptiming.timeThread("t1")
t2.start()

在你的 timeThread class 中,.run() 方法执行一个繁忙的循环:它连续显示经过的时间,没有任何暂停所以 CPU 变得疯狂,我猜OS 没有调度其他线程,那么。

在此循环中执行某种 time.sleep() - 应该会恢复正常。

旁注:为什么要在 guiThread class 构造函数中创建 UI 元素?对于 Qt,无论如何所有 UI 元素都属于主线程。正如@ekhumoro 所说,GUI 操作 必须 发生在主线程中,在您的代码中就是这种情况,尽管它是以一种令人困惑的方式编写的。就我个人而言,我会明确 UI 元素是在主线程中创建的,我会添加一个数据处理线程。