Imagine that you have a big function that locks / unlocks the mutex inside, and you want to break the function into smaller functions:
#include <pthread.h> class MyClass : public Uncopyable { public: MyClass() : m_mutexBuffer(PTHREAD_MUTEX_INITIALIZER), m_vecBuffer() {} ~MyClass() {} void MyBigFunction() { pthread_mutex_lock(&m_mutexBuffer); if (m_vecBuffer.empty()) { pthread_mutex_unlock(&m_mutexBuffer); return; } // DoSomethingWithBuffer1(); unsigned char ucBcc = CalculateBcc(&m_vecBuffer[0], m_vecBuffer.size()); // DoSomethingWithBuffer2(); pthread_mutex_unlock(&m_mutexBuffer); } private: void DoSomethingWithBuffer1() { // Use m_vecBuffer } void DoSomethingWithBuffer2() { // Use m_vecBuffer } private: pthread_mutex_t m_mutexBuffer; std::vector<unsigned char> m_vecBuffer; };
How do I lock / unlock a mutex inside smaller functions?
Do I have to unlock the mutex first, and then lock it immediately and finally unlock it before returning?
void DoSomethingWithBuffer1() { pthread_mutex_unlock(&m_mutexBuffer); pthread_mutex_lock(&m_mutexBuffer);
source share