I'm watching a video about mutex and RAII.
In the video the author explains that a good application of RAII (using an object to manage a resource) is a mutex. He has the following class:
class Lock {
private:
Mutext_t* m_pm;
public:
explicit Lock(Mutex_t* pm) { Mutex_lock(pm); m_pm = pm; };
~Lock() { Mutex_unlock(m_pm); };
};
I'm not sure how he implemented Mutex_unlock and Mutex_lock.
My question is: Is the following implementation comparable, and will it achieve the desired result of unlocking a mutex should the function that class object is instantiated in throw an exception?
mutex mu;
class Lock { // Lock will be destroyed if stack is unwound
private:
mutex* p_Mutex;
public:
explicit Lock(mutex* Mutex) {
lock_guard<mutex> u_Lock(*Mutex);
p_Mutex = Mutex;
};
};
void functionB() {
Lock myLock(&mu);
// .. Do stuff that throws an error.
// Unwind stack and destroy myLock, unlocking the mutex?
}
This is very much a simple implementation for learning purposes. Thanks for your help.