您好我正在使用PyQt4,我需要在QThread中实现锁,但是这个类没有像库线程一样实现的方法锁。 知道如何在这里实现锁定?
我有一个问题,如果我使用线程我实现这样的锁
class Example:
lock = threading.Lock()
def __init__(self)
pass
def run(self):
Example.lock.acquire()
.......
........
Example.lock.realease()
这是一样的吗?:
class Example(QtCore.QThread):
mutex = QtCore.QMutex())
def __init__(self)
pass
def run(self):
mutex.lock()
.......
........
mutex.unlock()
由于
答案 0 :(得分:5)
你想要QMutex课程。 Qt使用QtCore.QMutex.lock()和unlock()函数来锁定和解锁QThreads。
这是一个例子: https://github.com/Werkov/PyQt4/blob/master/examples/threads/waitconditions.py
编辑:尽管存在细微差别,但它们非常相似。http://doc.qt.io/qt-4.8/qmutex.html
QMutex类有效可以支持threading.Lock和threading.RLock行为。这些都应该彻底解释它们在标准实现中的使用和限制。
标准Qt的QMutex参考(所以用C ++编写),但原则相同。
EDIT2:
使用标准线程模块和QMutex类添加示例:
from PySide import QtCore
mutex = QtCore.QMutex()
class QtLock(QtCore.QThread):
def __init__(self, name):
super(QtLock, self).__init__()
self.name = name
def run(self):
for i in range(10):
mutex.lock()
print i, self.name,
mutex.unlock()
threads = []
for i in range(5):
name = chr(i + ord('a'))
threads.append(QtLock(name))
for thread in threads:
thread.start()
for thread in threads:
thread.wait()
当我运行QMutex示例时,我得到以下内容:
0 a 0 d 1 a 0 b 2 a 1 b 2 b 1 d 3 a 3 b 0 c 4 a 4 b 1 c 2 d 2 c 3 d 4 d 5 b 3 c 6 b 5 d 4 c 6 d 7 b 7 d 8 d 5 c 8 b 9 d 6 c 9 b 7 c 8 c 9 c 0 e 1 e 2 e 5 a 3 e 6 a 4 e 7 a 5 e 6 e 8 a 7 e 9 a 8 e 9 e
当我注释掉.lock()和.unlock()行时,我得到了这一点,展示了QMutex如何有效地获取并释放锁:
00 cd 1 d 2 0 e 1 e 21d ec 33 e 4 e 5 00 bd2 a 1 ec a4 d3 6 c 2154 d b a c 3 6 d 2e75 db 8 7a3 e 8 ce 9 b4 4ed b6 c 7 a 55 9b c d a8 c 6 9 6 b 7 b 8 b 9 c ba 7 a 8 a 9 a
同时,这里我的标准线程模块的代码几乎完全相同:
import threading
lock = threading.Lock()
class PyThread(threading.Thread):
def __init__(self, name):
super(PyThread, self).__init__()
self.name = name
def run(self):
for i in range(10):
lock.acquire()
print i, self.name,
lock.release()
threads = []
for i in range(5):
name = chr(i + ord('a'))
threads.append(PyThread(name))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
输出是:
0 a 1 a 2 a 3 a 4 a 5 a 6 a 7 a 8 a 9 a 0 b 1 b 2 b 3 b 4 b 5 b 0 c 1 c 6 b 7 b 8 b 9 b 2 c 3 c 4 c 5 c 6 c 0 d 7 c 8 c 0 e 1 e 9 c 1 d 2 e 2 d 3 d 4 d 5 d 6 d 7 d 8 d 9 d 3 e 4 e 5 e 6 e 7 e 8 e 9 e
同样,当我注释掉lock.acquire()和lock.release()时,我得到:
0 a 1 a 2 a 3 a 4 a 5 a 6 a 7 a 8 a 9 a 0 b 1 b 2 b 3 b 4 b 5 b 6 b 7 b 8 b 9 b 0 c 1 0 dc 2 c 3 c 4 c 5 1 d 2c 0 e 16 ed c 72 c e8 3 ec 3 d4 e4 9 5cd 5e d 6 6e d 7 d 87 e 8 ed 9 e 9 d