Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does pthread_cond_wait and pthread_mutex_unlock conflict?

I am implementing manual reset event using pthread in Linux which is similar to WaitForSingleEvent in Windows. I found this post

pthread-like windows manual-reset event

and follow it, however there a thing that confuse me:

void mrevent_wait(struct mrevent *ev) {
     pthread_mutex_lock(&ev->mutex);
     while (!ev->triggered)
         pthread_cond_wait(&ev->cond, &ev->mutex);
     pthread_mutex_unlock(&ev->mutex);
}
  • pthread_cond_wait: Atomically release mutex and cause the calling thread to block on the condition variable cond;
  • pthread_mutex_unlock: Attempts to unlock the specified mutex. If the mutex type is PTHREAD_MUTEX_NORMAL, error detection is not provided. If a thread attempts to unlock a mutex that is has not locked or a mutex which is unlocked, undefined behavior results.

What I am scare is when pthread_cond_wait release the mutex, then pthread_mutex_unlock may come undefined behavior (this kind of thing would drive me crazy, how come they not handle it :-D )

Thank you.

like image 578
longbkit Avatar asked Dec 03 '25 21:12

longbkit


1 Answers

The standard says:

Upon successful return, the mutex has been locked and is owned by the calling thread.

Which means that when returning, pthread_cond_wait atomically locks the associated mutex.

The workflow is like this:

  • You lock a mutex
    • pthread_cond_wait atomically blocks and unlocks the mutex (so other threads might get here)
    • When a condition arrives, pthread_cond_wait atomically returns and locks the mutex
  • You unlock the mutex

I don't think pthread_cond_wait blocks and unlocks

That's because you didn't read the link I provided.

These functions atomically release mutex and cause the calling thread to block on the condition variable cond;

like image 200
cnicutar Avatar answered Dec 06 '25 11:12

cnicutar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!