Back to Blog

Understanding pthread_cond_wait() and pthread_cond_signal()

pthread_cond_wait() is used to block the current thread, waiting for another thread to wake it up using pthread_cond_signal() or pthread_cond_broadcast. pthread_cond_wait() must be used in conjunction with a pthread_mutex. As soon as the pthread_cond_wait() function enters the waiting state, it automatically releases the mutex. When another thread wakes up this thread via pthread_cond_signal() or pthread_cond_broadcast, causing pthread_cond_wait() to proceed (return), this thread automatically reacquires the mutex.

The purpose of the pthread_cond_signal function is to send a signal to another thread that is currently in a blocked waiting state, allowing it to exit the blocked state and continue execution. If no thread is in a blocked waiting state, pthread_cond_signal will still return successfully.

Using pthread_cond_signal generally does not cause a "thundering herd" phenomenon; it sends a signal to at most one thread. If multiple threads are blocked waiting on this condition variable, then which thread receives the signal and resumes execution is determined by the priority of each waiting thread. If the threads have the same priority, then which thread receives the signal is determined by the length of their waiting time. However, in any case, a single pthread_cond_signal call sends a signal at most once.