pythonpython-3.xmultithreadingpyqt5qmutex

Is threading.Lock() compatible with QThread() and is QMutex() compatible with python threads?


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:

  1. Is threading.Lock() compatible with threads made with QThread()?

  2. 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().


Solution

  • TL;DR; it is indifferent to use them combined.


    The QThreads are not Qt Threads, that is they are not new threads but it is a class that manages the native threads of each OS and the same happens with the Python Threads that are also a wrapper to handle the native threads. And the same thing happens with the QMutex and threading.Lock() so it is indifferent to use one or the other because in the background you are using the native threads and mutex.