If I unlock a mutex in reverse order of locking them, is this susceptible to a deadlock?

foo() {
mutex_A.lock()
....
mutex_B.lock()

mutex_B.unlock()
mutex_A.unlock()

}

So the above is the psudo code that I wrote for my logic. Is it flawed?

Upvotes: 0

Views: 505

Answers (2)

Jarod42
Jarod42

Reputation: 217085

unlocking doesn't produce deadlock.

Important is order of lock, following might produce deadlock (each wait lock mutex locked by other function).

void problematic_foo() {
    mutex_A.lock()
    mutex_B.lock()

    mutex_B.unlock()
    mutex_A.unlock()
}

void problematic_bar() {
    mutex_B.lock()
    mutex_A.lock()

    mutex_A.unlock()
    mutex_B.unlock()
}

Note that in c++11, you might lock several mutexes at "once" with std::lock:

void foo() {
    std::lock(mutex_A, mutex_B);

    mutex_A.unlock()
    mutex_B.unlock()
}

Upvotes: 0

No, there is no possibility of a deadlock just from this code.

A deadlock is when two threads (or things) are waiting for each other. Unlocking a mutex doesn't wait for anything, so it can't cause a deadlock.

Upvotes: 4

Related Questions