本文共 2061 字,大约阅读时间需要 6 分钟。
作者:曾宏安,讲师。
我们在编写多线程程序时经常需要在线程之间实现通信,常见的机制有信号量和互斥锁。这里再向大家介绍一种用于实现线程间同步的机制——条件变量。
条件变量可以使线程睡眠等待直到某个条件满足为止。条件变量基本使用操作有两种:一、当判断条件不满足时,某些线程睡眠在相应的条件变量上;二、某些线程改变了条件,唤醒睡眠在条件变量上的其他线程。
为了在判断或是改变条件时防止竞争,条件变量通常和互斥锁结合在一起使用。条件变量类型为pthread_cond_t,互斥锁类型为pthread_mutex_t。
条件变量的创建和注销
int pthread_cond_init(pthread_cond_t *restrict cond,pthread_condattr_t *restrict cond_attr); // 创建
int pthread_cond_destroy(pthread_cond_t *cond); // 注销
条件变量的等待和激活
int pthread_cond_wait(pthread_cond_t *restrict cond,
该函数使当前线程释放互斥锁mutex并睡眠在条件变量cond上,正确返回时当前线程获得互斥锁mutex
int pthread_cond_timewait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex,const struct timespec *restrict abstime);
该函数功能同pthread_cond_wait,但睡眠时间不超过abstime,正确返回时当前线程获得互斥锁mutex
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);
下面我们看一个例子,了解一下条件变量的用法
#include <stdio.h>