Hi I am using PyQt4 and i need to implement locks in a QThread but this class does not have a method lock implemented like the library threading. Any idea how can I implement a lock here?
I have a question if i use threading i implement the lock like this
class Example:
lock = threading.Lock()
def __init__(self)
pass
def run(self):
Example.lock.acquire()
.......
........
Example.lock.realease()
is this the same?:
class Example(QtCore.QThread):
mutex = QtCore.QMutex())
def __init__(self)
pass
def run(self):
mutex.lock()
.......
........
mutex.unlock()
Thanks
You want the QMutex class. Qt uses the QtCore.QMutex.lock() and unlock() functions to lock and unlock QThreads.
Here's an example: https://github.com/Werkov/PyQt4/blob/master/examples/threads/waitconditions.py
EDIT: They're fairly similar although there are subtle differences.
http://www.laurentluce.com/posts/python-threads-synchronization-locks-rlocks-semaphores-conditions-events-and-queues/
http://doc.qt.io/qt-4.8/qmutex.html
The QMutex class effective can support both threading.Lock and threading.RLock behavior. Both these should thoroughly explain their use, limitations in standard implementations.
The QMutex reference for standard Qt (so it's written in C++), but the same principles hold.
EDIT2:
Adding in an example for both using the standard threading module and the QMutex class:
When I run the QMutex example, I get the following:
When I comment out the .lock() and .unlock() lines, I get this, showing how the QMutex effectively acquires and releases the lock:
Meanwhile, here I have almost the exact same code for the standard threading module:
And the output is:
Likewise, when I comment out the lock.acquire() and lock.release(), I get: