0

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.

  • 2
    `Lock` does not work at all. It is a trivially destructible type and does nothing at destructor. Mutex will be unlocked when `u_Lock` is destroyed. – user7860670 Oct 15 '19 at 13:47
  • 1
    Why wrap standard lock functionality, why not use e.g. `std::lock_guard` directly? – Some programmer dude Oct 15 '19 at 13:49
  • Have a lock and `std::lock_gaurd` and `std::scoped_lock` to see how to RAII a mutex. – NathanOliver Oct 15 '19 at 13:52
  • I suppose the video you have is more to explain the concept, not about the implementation. `Mutex_lock()` is a magic wand for "*I lock the mutex here in some way, which isn't important for the concept*". The concept of RAII is still valid - **you lock the mutex in constructor and release it in destructor** (though the video seems to have skipped over The Rule of Three, which is very important). – Yksisarvinen Oct 15 '19 at 13:53
  • It's probably worth highlighting at this point since BOTH samples fail to take it into consideration - the rule of 3 (or 5). You have to take care about the copying and assigning of the class – UKMonkey Oct 15 '19 at 13:54
  • @VTT What is the best way to build a mutex in a class such that it locks in the constructor and unlocks in the destructor? –  Oct 15 '19 at 13:56
  • You can check `std::lock_guard` implementation for example – user7860670 Oct 15 '19 at 14:11

0 Answers0