How to avoid deadlocks

Source: Internet
Author: User

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}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.