3

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.

Community
  • 1
  • 1
longbkit
  • 1,218
  • 1
  • 13
  • 20

1 Answers1

9

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;

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • In conclusion it's valid (and required) to unlock the mutex after `pthread_cond_wait`. – cnicutar Jun 30 '11 at 09:44
  • I don't think pthread_cond_wait blocks and unlocks. But if it first unlock the mutex and then try to lock back the mutex, I think it may lead to a deadlock here. And BTW, anyone knows why we must put pthread_cond_wait into a while loop? Can I just using an if statement? Thank you! – longbkit Jun 30 '11 at 09:52
  • 1
    @longbkit See my edited answer. Your second question is answered here: http://stackoverflow.com/questions/6505567/about-pthread-cond-signal-and-pthread-cond-wait/6507488#6507488 – cnicutar Jun 30 '11 at 09:56