1、int pthread_cond_init(pthread_cond_t * pCond , pthread_condattr_t * pAttr);
用于初始化申明的条件变量。 参数pCond指向用户分配的未初始化的条件变量,参数pAttr指定条件变量的属性;如果pAttr值为NULL,则条件变量的属性将以系统规定的默认属性初始化。
如果pCond指向一个已经被初始化的条件变量,函数行为将是不确定的:结果一,函数返回EBUSY;结果二,重新初始化得到一个新条件变量。
2、 int pthread_cond_wait(pthread_cond_t * pCond , pthread_mutex_t * pMutex)
用于使调用该函数的线程在条件变量pCond上阻塞。参数pCond指向条件变量,参数pMutex指向一个互斥体;条件变量总是和一个互斥体关联使用,互斥体保证所有线程等待该条件变量时的互斥访问。
pthread_mutex_lock(pMutex);
pthread_cond_wait(pCond , pMutex);
pthread_mutex_unlock(pMutex);
pthread_cond_wait(pCond , pMutex);
pthread_mutex_unlock(pMutex);
3、 int pthread_cond_timedwait(pthread_cond_t * pCond , pthread_mutex_t * pMutex , const struct timespec *pAbstime)
用途与
pthread_cond_wait()相似,只是加了一个等待时间。
pthread_cond_wait()会一直等待条件知道条件被触发,
pthread_cond_timedwait()多了一个超时控制,如果到了指定时间但条件还没被触发,函数将返回ETIMEDOUT。
4、int pthread_cond_signal(pthread_cond_t * pCond)
解除pCond上一个等待线程阻塞,如果没有线程在阻塞,该次调用不进行任何操作。
int pthread_cond_broadcast(pthread_cond_t * pCond)
解除pCond上所有阻塞的线程,如果没有线程在阻塞,该次操作不进行任何操作。广播触发解除多个阻塞的等待线程,这些线程将竞争以重新锁定互斥体,调度策略决定线程的顺序。
5、int pthread_cond_destroy(pthread_cond_t * pCond)
用于删除条件变量。成功返回0,如果条件变量还被某个线程持有,则函数返回EBUSY。
代码示例:
include <stdio.h>
include <sys/time.h>
include <unistd.h>
include <pthread.h>
include <errno.h>
pthread_t
thread
;
pthread_cond_t cond;
pthread_mutex_t mutex;
unsigned
char
flag = 1;
void
* thr_fn(
)
{
pthread_mutex_lock(&mutex);
/* 锁定互斥体 */
while
(flag)
{
printf(“
thread
sleep now\n”);
pthread_cond_wait(&cond, &mutex);
/* 以原子操作锁定条件变量等待信号,同时解除对互斥体
的锁定,线程处于阻塞状态,线程在收到触发信号后重
新锁
定
互斥体 */
}
pthread_mutex_unlock(&mutex);
/* 解除对互斥体的锁定 */
printf(“
thread
exit\n”);
}
int
main()
{
char
c ;
pthread_mutex_init(&mutex, NULL); /* 初始化互斥体 */
pthread_cond_init(&cond, NULL);
/* 初始化条件变量 */
if (0 != pthread_create(&thread, NULL, thr_fn, NULL))
/* 创建线程 */
{
printf(“error when create pthread,%d\n”, errno);
return
1;
}
while
((c = getchar()) != ‘q’);
printf(“Now terminate the
thread
!\n”);
flag = 0;
pthread_mutex_lock(&mutex);
/* 因为子线程在等待触发信号时解除对互斥体的锁定,所以在此可以锁
定互斥体 */
pthread_cond_signal(&cond);
/* 发触发信号唤醒阻塞在条件变量上的线程 */
pthread_mutex_unlock(&mutex);
/* 解除互斥体让阻塞线程重新锁定互斥体 */
printf(“Wait
for
thread
to exit\n”);
pthread_join(thread, NULL);
/* 等待子线程结束 */
printf(“Bye\n”);
return
0;
}