3
votes

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.

1

1 Answers

9
votes

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;