#include <iostream>
#include<pthread.h>
#include<unistd.h>
#include<time.h>
#include<stdlib.h>
using namespace std;
/*
测试条件变量
用到条件变量和线程锁 链表
例子为生产者和消费者,
原则是生产者有生产出物品,消费者才可以消费
*/
//结构体
typedef struct _node
{
int data;
struct _node *next_node;
} Node;
//头节点
Node*headNode=NULL; //初始化头节点为空
pthread_mutex_t mutex_t; //线程锁对象
pthread_cond_t cond_t; //条件变量对象
void*fun1(void*arg) //生产者
{
while(1) //无限生产
{
Node*newnode=new Node; //新建结构体对象
newnode->data=rand()%100;
pthread_mutex_lock(&mutex_t); //上锁
newnode->next_node=headNode;
headNode=newnode;
printf("====== fun1: %lu, %d\n", pthread_self(), newnode->data);
pthread_mutex_unlock(&mutex_t);//解锁
pthread_cond_signal(&cond_t);//发送条件变量信号
sleep(rand()%3+1);
}
return NULL;
}
void*fun2(void*arg)//消费者
{
while(1)
{
pthread_mutex_lock(&mutex_t);//上锁
if(headNode == NULL)
{
pthread_cond_wait(&cond_t,&mutex_t);//条件变量阻塞
}
Node*temp=headNode;
printf("====== fun2: %lu, %d\n", pthread_self(), headNode->data);
headNode=headNode->next_node;
delete temp;
pthread_mutex_unlock(&mutex_t);//解锁
sleep(rand()%6+1);
}
return NULL;
}
int main()
{
pthread_t pid1,pid2; //线程变量
pthread_mutex_init(&mutex_t,NULL);//线程锁初始化
pthread_cond_init(&cond_t,NULL);//条件变量初始化
pthread_create(&pid1,NULL,fun1,NULL);//创建线程
pthread_create(&pid2,NULL,fun2,NULL);//创建线程
pthread_join(pid1,NULL);//等待回收线程资源
pthread_join(pid2,NULL);//等待回收线程资源
pthread_mutex_destroy(&mutex_t);//销毁线程锁
pthread_cond_destroy(&cond_t);//销毁条件变量
return 0;
}