Does a mutex unlock when it comes out of scope?

c++, multithreading, mutex, pthreads

Solution

The mutex is not going out of scope in your examples; and there is no way for the compiler to know that a particular function needs calling at the end of the scope, so the first example does not unlock the mutex.

If you are using (error-prone) functions to lock and unlock the mutex, then you will need to ensure that you always call `unlock()` - even if the protected operation throws an exception.

The best way to do this is to use a RAII class to manage the lock, as you would for any other resource that needs releasing after use:

class lock_guard {
public:
    explicit lock_guard(mutex & m) : m(m) {mutex_lock(m);}
    ~lock_guard() {mutex_unlock(m);}

    lock_guard(lock_guard const &) = delete;
    void operator=(lock_guard &) = delete;

private:
    mutex & m;
};

// Usage
{
    lock_guard lock(myMutex);
    shared_resource++;
} // mutex is unlocked here (even if an exception was thrown)

In modern C++, use `std::lock_guard` or `std::unique_lock` for this.

Problem

Simple question - basically, do I have to unlock a mutex, or can I simply use the scope operators and the mutex will unlock automatically? ie: ``` { pthread_mutex_lock (&myMutex); sharedResource++; } // my mutex is now unlocked? ``` or should I: ``` { pthread_mutex_lock (&myMutex); sharedResource++; pthread_mutex_unlock (&myMutex); } ```

Original source