Mutexes are not the only synchronization mechanisms available. For some more complex tasks, the GNU C Library also implements condition variables, which allow the programmer to think at a higher level when solving complex synchronization problems. They are used to synchronize threads waiting on a certain condition to happen.
The fundamental data type for condition variables is the cnd_t:
The following functions are used for working with condition variables:
Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.
cnd_initinitializes a new condition variable, identified by cond.This function may return
thrd_success,thrd_nomem, orthrd_error.
Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.
cnd_signalunblocks one thread that is currently waiting on the condition variable pointed to by cond. If a thread is successfully unblocked, this function returnsthrd_success. If no threads are blocked, this function does nothing and returnsthrd_success. Otherwise, this function returnsthrd_error.
Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.
cnd_broadcastunblocks all the threads that are currently waiting on the condition variable pointed to by cond. This function returnsthrd_successon success. If no threads are blocked, this function does nothing and returnsthrd_success. Otherwise, this function returnsthrd_error.
Preliminary: | MT-Safe | AS-Unsafe lock | AC-Unsafe lock | See POSIX Safety Concepts.
cnd_waitatomically unlocks the mutex pointed to by mutex and blocks on the condition variable pointed to by cond until the thread is signaled bycnd_signalorcnd_broadcast. The mutex is locked again before the function returns.This function returns either
thrd_successorthrd_error.
Preliminary: | MT-Safe | AS-Unsafe lock | AC-Unsafe lock | See POSIX Safety Concepts.
cnd_timedwaitatomically unlocks the mutex pointed to by mutex and blocks on the condition variable pointed to by cond until the thread is signaled bycnd_signalorcnd_broadcast, or until the calendar time pointed to by time_point has been reached. The mutex is locked again before the function returns.As for
mtx_timedlock, since this function takes an absolute time, if a duration is required, the calendar time must be calculated manually. See Time Basics, and Calendar Time.This function may return
thrd_success,thrd_nomem, orthrd_error.
Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.
cnd_destroydestroys the condition variable pointed to by cond. If there are threads waiting on cond, the behavior is undefined.