生产者消费者

生产者消费者

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
struct Node{
	int val;
	Node* next;
};

pthread_mutex_t mutex;  //锁的声明
pthread_cond_t cond;    //条件变量声明
Node* head = NULL;

//生产者
void* producter(void* argv){
	while(1){
        // 生产一个节点
		Node* p = (Node*)malloc(sizeof(Node));
		p->val = rand() % 1000;
        
        //放东西的时候要加锁
		pthread_mutex_lock(&mutex);
		printf("sheng chan le %d\n", p->val);
		p->next = head;
		head = p;
		pthread_mutex_unlock(&mutex);
        //放完解锁
        
		sleep(1);
        // 当有物品时通知消费者去拿
		pthread_cond_signal(&cond);
	}
}
// 消费者
void* customer(void* argv){
	Node* p = NULL; 
	while(1){
		pthread_mutex_lock(&mutex);
		if (head == NULL) {
            // pthread_cond_wait函数当没pthread_cond_signal来通知的时候阻塞,解锁
            // 当来通知的时候往下执行,加锁
			pthread_cond_wait(&cond, &mutex);
		}
		if (head == NULL) {
            // 当生产者发出信号的时候可能有多名消费者收到信号,但是获得锁的只有一个,其他的收到信号但是没有得到锁,当物品只有一个的时候,一个消费者着拿走head变为NULL并释放锁,此时另一个消费者再来拿的时候head已经变为NULL发生段错误,所以这时不能往下执行但是他已经获得了锁,此时要将锁释放。
			pthread_mutex_unlock(&mutex);
			continue;
		}
		printf("xiao fei le %d\n", head->val);
		p = head;
		head = head->next;
		pthread_mutex_unlock(&mutex);
		free(p);
		p = NULL;
	}
}
int main()
{
	pthread_mutex_init(&mutex, NULL);  //锁的初始化
	pthread_cond_init(&cond, NULL);    //条件变量初始化

	pthread_t thread1;
	pthread_create(&thread1, NULL, customer, NULL);

	pthread_t thread2;
	pthread_create(&thread2, NULL, producter, NULL);

	pthread_join(thread1, NULL);
	pthread_join(thread2, NULL);

	pthread_mutex_destroy(&mutex);  //锁的回收
	pthread_cond_destroy(&cond);    //条件变量回收
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值