使用条件变量实现生产者和消费者模型,生产者有5个,往链表头部添加节点,消费者也有5个,删除链表头部的节点
具体相关函数查看本人上一片博客
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<pthread.h>
//创建条件变量
pthread_cond_t cond;
//创建互斥锁
pthread_mutex_t mutex;
//链表节点类型
struct Node
{
int number;//节点数据值
struct Node*next;//指向当前节点类型后继节点的地址
};
//创建头结点
struct Node*head=NULL;
//生产者
//此处用的是链表没有上限
void* producer(void* arg)
{
//一直生产
while(1)
{
pthread_mutex_lock(&mutex);
//创建新节点
struct Node*newNode=(struct Node*)malloc(sizeof(struct Node));
//初始化节点
newNode->number=rand()%1000;//获取随机数,1000以内
//节点的连接,添加到链表的头部,新节点就是新的头结点
newNode->next=head;
//head指针前移
head=newNode;
printf("生产者,id:%ld ,number:%d\n",pthread_self(),newNode->number);
pthread_mutex_unlock(&mutex);
//生产了任务,通知消费者来消费啦!
pthread_cond_broadcast(&cond);
//生产的慢一点哦
sleep(rand()%3);//0 1 2
}
return NULL;
}
//消费者
//消费者有下限,如果链表为空,就要阻塞消费者线程
void* consumer(void*arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
// 一直消费, 删除链表中的一个节点
//if(head == NULL)有bug:
/*当任务队列为空, 所有的消费者线程都会被这个函数阻塞 pthread_cond_wait(&cond, &mutex);
当生产者生产了1个节点, 调用 pthread_cond_broadcast(&cond); 唤醒了所有阻塞的线程
- 有一个消费者线程通过 pthread_cond_wait()加锁成功, 其余没有加锁成功的线程继续阻塞
- 加锁成功的线程向下运行, 并成功删除一个节点, 然后解锁
- 没有加锁成功的线程解除阻塞继续抢这把锁, 另外一个子线程加锁成功
- 但是这个线程删除链表节点的时候链表已经为空了, 后边访问这个空节点的时候就会出现段错误
解决方案:
- 需要循环的对链表是否为空进行判断, 需要将if 该成 while
*/
while(head==NULL)
{
/*
线程加互斥锁成功,但是线程阻塞在这行代码上,
锁还没解开,其他线程在访问这把互斥锁的时候也会被阻塞在这把互斥锁上,生产者也会被阻塞,造成死锁
但是并没有死锁,why?
pthread_cond_wait()此函数内部会自动将线程拥有的锁2.解开
当消费者线程解除阻塞之后,会自动将这把锁3.锁上,
这时候当前这个线程又重新拥有了这把互斥锁
*/
//1.阻塞消费者线程
pthread_cond_wait(&cond,&mutex);
}
//链表的头结点,将其删除
struct Node*node=head;
printf("消费者,id:%ld ,number:%d\n",pthread_self(),node->number);
head=node->next;
free(node);
pthread_mutex_unlock(&mutex);
sleep(rand()%3);
}
return NULL;
}
int main()
{
//初始化
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL);
//创建两个数组,这两个数组里面来存储子线程创建出来的ID
pthread_t t1[5],t2[5];
for(int i=0;i<5;i++){
pthread_create(&t1[i],NULL,producer,NULL);
}
for(int i=0;i<5;i++){
pthread_create(&t2[i],NULL,consumer,NULL);
}
//线程资源的释放
for(int i=0;i<5;i++){
//阻塞等待子线程的退出
pthread_join(t1[i],NULL);
pthread_join(t2[i],NULL);
}
//销毁条件变量
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}