pthread condition提供如下函数,用于线程间同步的通知:
int pthread_cond_init(pthread_cond_t *cond,pthread_condattr_t *cond_attr);//创建一个condition的内核变量
int pthread_cond_wait(pthread_cond_t *cond,pthread_mutex_t *mutex);//等待内核变量变为signaled
int pthread_cond_timewait(pthread_cond_t *cond,pthread_mutex *mutex,const timespec *abstime);//在指定时间内等待内核心变量变为signaled
int pthread_cond_destroy(pthread_cond_t *cond);//“析构”一个condition的内核变量
int pthread_cond_signal(pthread_cond_t *cond);//把内核变量置为signaled,指定一个等待线程激活,但不能指定特定线程
int pthread_cond_broadcast(pthread_cond_t *cond);//把内核变量置为signaled,指定所有等待线程激活
condition可以在线程间同步条件,当条件触发后,“生产者”线程通过pthread_cond_signal/pthread_cond_broadcast通知正在pthread_cond_wait/pthread_cond_timewait的“消费者”线程。
如下例:
假设临界变量x,y,“消费者“线程在x>y的时候执行func(x,y)函数,”生产者“线程执行某个动作改变x,y的值。
pthread_cond_t cond;
pthread_mutex_t mutex;
int x,y;//临界变量
void func(int x, int y)
{
printf("x is greater than y, the value is x,y = %d,%d\n", x, y);
}
//生产者的线程执行函数
void threadfacter()
{
while(1)
{
pthread_mutex_lock(&mutex);
//do some thing on x, y
if(x > y)
{
pthread_cond_broadcast(&cond);//如果条件符合,则通知消费者线程
}
pthread_mutex_unlock(&mutex);
}
}
void threadcomsumer()
{
while(1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex) //如果条件不符合,则释放mutex锁,并等待。如果条件符合,表示条件已经符合,并且尝试再对mutex加锁,如果加锁成功,pthread_cond_wait返回0
{
func(x,y);
}
pthread_mutex_unlock(&mutex);//
}
}
int main()
{
pthread_cond_init(&cond, NULL);
pthread_mutex_init(&mutex, NULL);
pthread_t threadfactorID, threadcomsumerID;
pthread_create(&threadfactorID, NULL, (void *) threadfacter, NULL);
pthread_create(&threadcomsumerID, NULL, (void *) threadcomsumer, NULL);
pthread_join(threadfactorID);
pthread_join(threadcomsumerID);
}