I'm using Python 3.7 (with PyQt5 for the GUI) on a Windows 10 computer. My application needs some multithreading. To do that, I use QThread()
.
I need to protect some code with a mutex. I figured I've got the following two options: protect it with a lock from the Python threading
module or with a QMutex()
.
1. Protection with threading.Lock()
This is how I make my mutex:
import threading
...
self.mutex = threading.Lock()
and how I use it:
def protected_function(self):
if not self.mutex.acquire(blocking=False):
print("Could not acquire mutex")
return
# Do very important
# stuff here...
self.mutex.release()
return
You can find the Python docs here: https://docs.python.org/3/library/threading.html#threading.Lock
2. Protection with QMutex()
To make the mutex:
from PyQt5.QtCore import *
...
self.mutex = QMutex()
and how to use it:
def protected_function(self):
if not self.mutex.tryLock():
print("Could not acquire mutex")
return
# Do very important
# stuff here...
self.mutex.unlock()
return
You can find the Qt5 docs on QMutex()
here: http://doc.qt.io/qt-5/qmutex.html
3. Compatibility
I would like to know:
Is
threading.Lock()
compatible with threads made withQThread()
?Is
QMutex()
compatible with normal Python threads?
In other words, is it a big deal if these things get a bit mixed around? - For example: a few python threads run in an application, next to some QThread's, and some stuff is protected by threading.Lock()
, other stuff by QMutex()
.