#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
//互斥量
pthread_mutex_t mutex;
//条件变量
pthread_cond_t cond;
//定义结构体
typedef struct Node
{
int data;
struct Node *next;
}NODE;
//头插法
NODE *head = NULL;
//生产者处理函数
void *producer(void *arg)
{
//定义一个节点
NODE *pNode = NULL;
while(1)
{
//开辟堆内存
pNode = (NODE *)malloc(sizeof(NODE));
if(pNode==NULL)
{
printf("malloc error\n");
exit(-1);
}
//随机数赋值
pNode->data = rand()%1000;
printf("P:[%d]\n", pNode->data);
//加锁
pthread_mutex_lock(&mutex);
pNode->next = head;
head = pNode;
pthread_mutex_unlock(&mutex);
//通知消费者线程解除阻塞
pthread_cond_signal(&cond);
sleep(rand()%3);
}
}
//消费者线程
void *consumer(void *arg)
{
NODE *cNode = NULL;
while(1)
{
pthread_mutex_lock(&mutex);
//head为空阻塞
if(head==NULL)
{
pthread_cond_wait(&cond, &mutex);
}
printf("C:[%d]\n", head->data);
cNode = head;
head = head->next;
//解锁
pthread_mutex_unlock(&mutex);
//删除头节点
free(cNode);
cNode = NULL;
sleep(rand()%3);
}
}
int main()
{
int ret;
pthread_t ptid, ctid;
//初始化互斥量
pthread_mutex_init(&mutex, NULL);
//初始化条件变量
pthread_cond_init(&cond, NULL);
//创建生产者
ret = pthread_create(&ptid, NULL, producer, NULL);
if(ret!=0)
{
printf("pthread_create error, [%s]\n", strerror(ret));
return -1;
}
//创建消费者
ret = pthread_create(&ctid, NULL, consumer, NULL);
if(ret!=0)
{
printf("pthraed_create error, [%s]\n", strerror(ret));
return -1;
}
//阻塞线程结束
pthread_join(ptid, NULL);
pthread_join(ctid, NULL);
//释放互斥锁
pthread_mutex_destroy(&mutex);
//释放条件变量
pthread_cond_destroy(&cond);
return 0;
}