条件变量和互斥量的初始化和销毁类似(一个条件变量总是和一个mutex搭配使用的):
1.初始化条件变量
2.销毁条件变量
3.在某条件下等待
调用这个等待函数的时候这个函数其实做了三件事:
首先释放mutex;然后开始进行阻塞式等待;当被唤醒时,重新获得mutex并返回
4.唤醒执行流
程序示例:基于单链表的生产者——消费者模型
运行结果:
程序代码:
#include <stdio.h>
#include <malloc.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
//单链表的基本操作
typedef struct Node
{
int _data;
struct Node *pNext;
}Node,*pNode;
static pNode alloc_node(int data)
{
pNode _h = (pNode)malloc(sizeof(Node));
_h->_data = data;
_h->pNext = NULL;
}
//初始化
void init_list(pNode *_h)
{
*_h = alloc_node(0);
}
//头插
void push_list(pNode _h, int data)
{
pNode _n = alloc_node(data);
_n->pNext = _h->pNext;
_h->pNext = _n;
}
//判空
int is_empty(pNode _h)
{
return ((_h->pNext==NULL)?1:0);
}
//删除结点
void delete_node(pNode _tmp)
{
if(!_tmp)
{
free(_tmp);
}
}
//头删
void pop_list(pNode _h, int *_o)
{
if(!is_empty(_h))
{
pNode _tmp = _h->pNext;
_h->pNext = _tmp->pNext;
*_o = _tmp->_data;
delete_node(_tmp);
}
else
{
printf("list is empty...\n");
}
}
//销毁单链表
void destroy_list(pNode _h)
{
int data;
while(!is_empty(_h));
{
pop_list(_h, &data);
}
delete_node(_h);
}
//打印单链表
void show_list(pNode _h)
{
pNode p = _h->pNext;
while(p)
{
printf("%d->", p->_data);
p = p->pNext;
}
printf("\n");
}
//消费者
static void *consumer(void *arg)
{
pNode h = (pNode) arg;
for(; ;)
{
pthread_mutex_lock(&lock);
int data = rand()%1234;
while(is_empty(h))//判断:单链表为空时则不能消费
{
printf("can't consume now...\n'");
pthread_cond_wait(&cond, &lock);//等待
}
pop_list(h, &data);
printf("product done...%d\n", data);
pthread_mutex_unlock(&lock);
}
}
//生产者
static void *producer(void *arg)
{
pNode h = (pNode) arg;
for(; ;)
{
pthread_mutex_lock(&lock);
int data = rand()%1234;
push_list(h, data);
printf("now can consuming...%d\n", data);
pthread_mutex_unlock(&lock);
sleep(1);
pthread_cond_signal(&cond);//唤醒消费者
}
}
int main()
{
Node *head = NULL;
init_list(&head);
pthread_t id1, id2;
pthread_create(&id1, NULL, consumer, head);
pthread_create(&id2, NULL, producer, head);
pthread_join(id1, NULL);
pthread_join(id2, NULL);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
// for( ; i<10; i++)
// {
// push_list(head, i);
// show_list(head);
// sleep(1);
// }
//int data = 0;
// for(; i>5; i--)
// {
// pop_list(head, &data);
// show_list(head);
// sleep(1);
// }
return 0;
}