Search code examples
cmultithreadingpthreadsundefined-behaviorcompiler-specific

Unlocking an already unlocked thread


In an already running old code, i have found a place where they were trying to unlock an already unlocked mutex.

I am clear that unlocking an already unlocked mutex will lead to undefined behaviour.

But my doubts are

  1. Am I able to predict the behaviour by checking the compiler documentation?
  2. Is there any chances that it may lead to blocking of the thread (deadlock)?
  3. Undefined behaviour will be seen on the pthread_mutex_unlock where it was unlocking the already unlocked thread? Or the undefined behaviour can be seen on any of the next pthread calls ?

Solution

  • Am I able to predict the behaviour by checking the compiler documentation?

    If the compiler says what the behavior will be, then if you use that compiler (and it retains that behavior) then you can rely on that behavior.

    Is there any chances that it may lead to blocking of the thread (deadlock)?

    Yes. UB can lead to anything. If, for example, the unlock function unconditionally decrements a lock count, it could underflow, keeping the mutex locked forever.

    Undefined behaviour will be seen on the pthread_mutex_unlock where it was unlocking the already unlocked thread? Or the undefined behaviour can be seen on any of the next pthread calls ?

    You are asking how the behavior is defined. It is undefined. Anything can happen at any time after this point, at least as far as the POSIX pthreads standard says. Unless something else specifies what will happen, it can be anything at all and you officially have no right to complain.