在PyQt5中,你可以使用QMutex
(互斥锁)来实现线程锁,以避免多个线程同时访问共享资源而引发冲突。下面是一个简单的示例,展示了如何在多线程中使用线程锁:
import sys
from PyQt5.QtCore import QThread, QObject, pyqtSignal, QMutex
class WorkerThread(QThread):
valueChanged = pyqtSignal(int)
def __init__(self, mutex):
super(WorkerThread, self).__init__()
self.mutex = mutex
def run(self):
for i in range(5):
self.mutex.lock() # 锁定互斥锁
self.valueChanged.emit(i)
self.mutex.unlock() # 解锁互斥锁
self.sleep(1)
class MyObject(QObject):
def __init__(self):
super(MyObject, self).__init__()
self.mutex = QMutex()
def handleValueChange(self, value):
self.mutex.lock() # 锁定互斥锁
print(f"Received value: {value}")
self.mutex.unlock() # 解锁互斥锁<