from PyQt5.QtCore import QMutex mutex = QMutex() def function_a(): mutex.lock() # ... do some thread-safe work ... mutex.unlock() def function_b(): mutex.lock() # ... do some thread-safe work ... mutex.unlock()
from PyQt5.QtCore import QMutex mutex = QMutex(QMutex.Recursive) def function_a(): mutex.lock() # ... do some thread-safe work ... function_b() mutex.unlock() def function_b(): mutex.lock() # ... do some thread-safe work ... mutex.unlock()In this example, we have two functions that both need to access the mutex. However, function_a() calls function_b() while the mutex is locked. This would normally cause a deadlock, but we use a recursive mutex to avoid this issue. When the same thread tries to lock a recursive mutex twice, it is allowed to proceed without blocking. Overall, QMutex is a useful tool for ensuring thread safety in Python PyQt5 applications. It is a part of the QtCore module in the PyQt5 package.