How can I avoid deadlocks when using mutex for synchronization?
When we lock a piece of code and forget to unlock it, our program may have a deadlock. We usually avoid such errors with caution, but we cannot guarantee that they will never be committed. When there is a deadlock and a large amount of code, the problem is often difficult to find, because the debugging of multi-threaded programs is often very troublesome.
Is there a way to implement the automatic unlocking mechanism? Of course! We can easily think of the class constructor and destructor, because the two will be automatically called when the object is created and destroyed.
Reference code:
#include <pthread.h>class CMutexLock{ public: CMutexLock() { pthread_mutex_init(&m_lock, NULL); } ~CMutexLock() { pthread_mutex_destroy(&m_lock); } void lock() { pthread_mutex_lock(&m_lock); } void unlock() { pthread_mutex_unlock(&m_lock); } private: pthread_mutex_t m_lock;};class CAutoLock{ public: CAutoLock(CMutexLock& mutexLock):m_mutexLock(mutexLock) { m_mutexLock.lock(); } ~CAutoLock() { m_mutexLock.unlock(); } private: CMutexLock& m_mutexLock;};
The usage of these two classes is simple:
Define a cmutexlock object (such as mutexlock), and then define the temporary variables of cautolock in the code area that requires mutual access. For example:
{Cautolock autolock (mutexlock); critical code}