Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

414 Threads Chapter 11


variable, but if the condition variable is allocated dynamically, we can use the
pthread_cond_initfunction to initialize it.
We can use the pthread_cond_destroyfunction to deinitialize a condition
variable beforefreeing its underlying memory.

#include <pthread.h>

int pthread_cond_init(pthread_cond_t *restrictcond,
const pthread_condattr_t *restrictattr);

int pthread_cond_destroy(pthread_cond_t *cond);

Both return: 0 if OK, error number on failure

Unless you need to create a conditional variable with nondefault attributes, theattr
argument topthread_cond_initcan be set toNULL.Wewill discuss condition
variable attributes in Section 12.4.3.
We usepthread_cond_waitto wait for a condition to be true. A variant is
provided to return an error code if the condition hasn’t been satisfied in the specified
amount of time.

#include <pthread.h>

int pthread_cond_wait(pthread_cond_t *restrictcond,
pthread_mutex_t *restrict mutex);

int pthread_cond_timedwait(pthread_cond_t *restrictcond,
pthread_mutex_t *restrict mutex,
const struct timespec *restrict tsptr);

Both return: 0 if OK, error number on failure

The mutex passed topthread_cond_wait protects the condition. The caller
passes it locked to the function, which then atomically places the calling thread on the
list of threads waiting for the condition and unlocks the mutex. This closes the window
between the time that the condition is checked and the time that the thread goes to sleep
waiting for the condition to change, so that the thread doesn’t miss a change in the
condition. Whenpthread_cond_waitreturns, the mutex is again locked.
Thepthread_cond_timedwaitfunction provides the same functionality as the
pthread_cond_waitfunction with the addition of the timeout (tsptr). The timeout
value specifies how long we arewilling to wait expressed as atimespecstructure.
Just as we saw in Figure11.13, we need to specify how long we arewilling to wait
as an absolute time instead of a relative time. For example, suppose we arewilling to
wait 3 minutes. Instead of translating 3 minutes into atimespecstructure, we need to
translate now+3minutes into atimespecstructure.
We can use theclock_gettimefunction (Section 6.10) to get the current time
expressed as atimespecstructure. However,this function is not yet supported on all
platforms. Alternatively, we can use thegettimeofdayfunction to get the current
time expressed as atimevalstructureand translate it into atimespecstructure. To
Free download pdf