嗨,我正在使用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()

谢谢

最佳答案

您需要QMutex类。 Qt使用QtCore.QMutex.lock()和unlock()函数来锁定和解锁QThreads。

这是一个例子:
https://github.com/Werkov/PyQt4/blob/master/examples/threads/waitconditions.py

编辑:尽管有细微的差别,但它们相当相似。

http://www.laurentluce.com/posts/python-threads-synchronization-locks-rlocks-semaphores-conditions-events-and-queues/

http://doc.qt.io/qt-4.8/qmutex.html

有效的QMutex类可以支持threading.Lock和threading.RLock行为。这两方面都应彻底解释其用法,以及标准实现中的局限性。

标准Qt的QMutex引用(因此它是用C++编写的),但原理相同。

编辑2:

添加一个使用标准线程模块和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

09-27 03:33