python - 为什么 QThread 只打印两个线程调用之一?

标签 python pyqt pyside qthread

from PySide.QtCore import *
from PySide.QtGui import *
import time as t


class WorkerThread(QThread):
    def _init_(self, mw):
    super(WorkerThread, self)._init_(mw)
    self.gameName = ""

def setGameName(self, currGameName):
    self.gameName = currGameName

def run(self):
    print self.gameName

class GG(object):
workerThread = WorkerThread()
def startThread(self,stringer):
    self.workerThread.setGameName(stringer)
    self.workerThread.start()

harro = GG()
harro.startThread("hello")
harro.startThread("hi")
t.sleep(60)

这只会打印“hi”而不是“hello”。为什么不打印两者?我将如何更改它以便同时打印两者?

最佳答案

startThread 的第二次调用取消了第一次。该线程没有时间打印您再次调用它要求打印“hi”的“hello”。 您可以在 QThread.start() 之后调用 QThread.wait() 以等待线程完成。

一个工作示例(同样,具有正确的标识):

class WorkerThread(QThread):
    def _init_(self, mw):
        super(WorkerThread, self)._init_(mw)
        self.gameName = ""

    def setGameName(self, currGameName):
        self.gameName = currGameName

    def run(self):
        print self.gameName

class GG(object):
     workerThread = WorkerThread()

     def startThread(self,stringer):
        self.workerThread.setGameName(stringer)
        self.workerThread.start()
        self.workerThread.wait()

harro = GG()
harro.startThread("hello")
harro.startThread("hi")

此示例将在线程运行时卡住用户界面。 所以对于更复杂的任务,你应该使用信号和槽机制。

关于python - 为什么 QThread 只打印两个线程调用之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28690578/

相关文章:

python - 使用 __del__ 观察 Python 和 PyQt 中的对象破坏

python - "QPainter::begin: Paint device returned engine == 0, type: 1"

c++ - 覆盖 QIODevice 子类中的 readData 返回不正确的结果

python - Django:使用 L10N 将 DateTimeField 转换为字符串

python - Pandas 中分组值的堆叠直方图

python - 名称错误 : name 'scipy' is not defined

python - 如何从复选框中获取文本?

php - 将河豚加密算法从 php 转换为 python

python - 异步Python函数处理PHP

python - 如何更改按钮边框半径