1、条件变量:条件变量是用来等待而不是用来上锁的。条件变量用来自动阻塞一个线程,直到某特殊情况发生为止。通常条件变量和互斥锁同时使用。条件变量使我们可以睡眠等待某种条件出现。条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作:一个线程等待"条件变量的条件成立"而挂起。
2、⼀一个线程可以调⽤用pthread_cond_wait在⼀一个Condition Variable上阻塞等待,这个函数做以下三步操作:
3、 条件变量分为两部分: 条件和变量. 条件本身是由互斥量保护的. 线程在改变条件状态前先要锁住互斥量. 它 利用线程间共享的全局变量进行同步的一种机制。1). 释放Mutex
2). 阻塞等待
3). 当被唤醒时,重新获得Mutex并返回
相关的函数如下:
int pthread_cond_init(pthread_cond_t *cond,pthread_condattr_t *cond_attr);
int pthread_cond_wait(pthread_cond_t *cond,pthread_mutex_t *mutex);
int pthread_cond_timewait(pthread_cond_t *cond,pthread_mutex *mutex,const timespec *abstime);
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);
pthread_cond_timedwait函数还有⼀一个额外的参数可以设定等待超时,如果到达了abstime所指定的 时刻仍然没有别的线程来唤醒当前线程,就返回ETIMEDOUT。一个线程可以
调用pthread_cond_signal唤醒在某个Condition Variable上等待的另⼀一个线程,也可以调⽤pthread_cond_broadcast唤醒在这个Condition Variable上等待的所有线程。
4、生产者消费者模式(基于单链表)
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
typedef struct _list{
struct _list *next;
int _val;
}product_list;
product_list *head = NULL;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t need_product = PTHREAD_COND_INITIALIZER;
void init_list(product_list *list)
{
if(list != NULL)
{
list->next = NULL;
list->_val = 0;
}
}
void* consumer(void *_val)
{
product_list *p = NULL;
for(;;)
{
pthread_mutex_lock(&lock);
while(NULL == head)
{
pthread_cond_wait(&need_product, &lock);
}
p = head;
head = head->next;
p->next = NULL;
pthread_mutex_unlock(&lock);
printf("consum success, data is : %d\n",p->_val);
free(p);
p = NULL;
}
return NULL;
}
void* product(void * _val)
{
for(;;)
{
sleep(1);
product_list *p = malloc(sizeof(product_list));
pthread_mutex_lock(&lock);
init_list(p);
p->_val = rand()%1000;
p->next = head;
head = p;
pthread_mutex_unlock(&lock);
printf("call consumer , product success, data is : %d\n",p->_val);
pthread_cond_signal(&need_product);
}
}
int main()
{
pthread_t t_product;
pthread_t t_consumer;
pthread_create(&t_product, NULL, product, NULL);
pthread_create(&t_consumer, NULL, consumer, NULL);
pthread_join(t_product, NULL);
pthread_join(t_consumer, NULL);
return 0;
}