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);
}
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.
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:
pthread_cond_wait atomically blocks and unlocks the mutex (so other threads might get here)pthread_cond_wait atomically returns and locks the mutexI 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With