from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import time
import sys
import numpy as np
class Mainthread(QThread):
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.running = None
self.mutex = QMutex()
def run(self):
while self.running:
self.mutex.lock()
print ("test")
time.sleep(1)
self.mutex.unlock()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.mainthread = Mainthread(self)
self.mainthread.running = True
self.mainthread.start()
self.mainthread1 = Mainthread(self)
self.mainthread1.running = True
self.mainthread1.start()
app = QApplication(sys.argv)
mainwindow = MainWindow()
mainwindow.show()
app.exec_()
我有这段代码,我运行同一个
MainThread
类的两个实例。
我期待的是打印
mainthread
的消息(即“测试”),然后等待一秒钟,然后打印mainthread1
的消息。相反,看起来两个线程都在同时运行。我有什么遗漏的吗?
在您的代码中,每个线程创建自己单独的互斥体,因此两者之间没有强制关系。首先创建一个互斥体,然后将其传递给线程。
我已添加到测试打印中以识别哪个线程正在执行此操作。
import time
import sys
from PyQt5.QtCore import QThread, QMutex
from PyQt5.QtWidgets import QMainWindow, QApplication
class Mainthread(QThread):
def __init__(self, mutex, parent, suffix=""):
super().__init__(parent)
self.parent = parent
self.running = None
self.mutex = mutex
self.suffix = suffix
def run(self):
while self.running:
self.mutex.lock()
print (f"Test from mainthread{self.suffix}")
time.sleep(1)
self.mutex.unlock()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
mutex = QMutex()
self.mainthread = Mainthread(mutex, self)
self.mainthread.running = True
self.mainthread.start()
self.mainthread1 = Mainthread(mutex, self, "1")
self.mainthread1.running = True
self.mainthread1.start()
app = QApplication(sys.argv)
mainwindow = MainWindow()
mainwindow.show()
app.exec_()
注意:我没有安装 PyQt5(在我的架构上这样做很棘手),但我在 PySide6 中对此进行了测试,据我所知,行为应该是一致的。