用条件变量实现生产者-消费者模型

首先介绍一下条件变量

 


下面用条件变量来实现生产者-消费者模型

大体思路如下:生产者为链表“生产”结点,消费者“消费”结点,如果链表中没有结点,则阻塞消费者线程

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <pthread.h>
#include <ctime>

pthread_mutex_t mutex;
pthread_cond_t cond;

struct Node{
	int val;
	Node* next;
	Node(int _val): val(_val), next(NULL){}
};

Node* head;

void Print(Node* h) {
	while (h) {
		printf("%d->", h->val);
		h = h->next;
	}
	printf("\n");
}

void* producer(void* argc) {
	srand(time(NULL));
	while (1) {
		int val = rand() % 10;
		Node* cur = new Node(val);
        // 生产者开始生产结点
		pthread_mutex_lock(&mutex);
		cur->next = head;
		head = cur;
		Print(head);
		pthread_mutex_unlock(&mutex);
        // 生产者生产完后唤醒消费者
		pthread_cond_signal(&cond);
		sleep(1);
	}	
	return NULL;
}

void* customer(void* argc) {
	while (1) {
		pthread_mutex_lock(&mutex);
		if (head == NULL) { // 如果链表中还没有结点,则阻塞线程
			printf("wait\n");
			pthread_cond_wait(&cond, &mutex);
		} 
        // 消费者开始消费结点
		Node* tmp = head;
		printf("tmp == %d\n", tmp->val);
		head = head->next;
		pthread_mutex_unlock(&mutex);
		delete tmp;
		sleep(2);
	}
	return NULL;
}



int main() {
	pthread_t p1, p2; // 创建两个线程,p1作为生产者,p2作为消费者
	pthread_create(&p1, NULL, producer, NULL);
	pthread_create(&p2, NULL, customer, NULL);

	pthread_mutex_init(&mutex, NULL); // 初始化互斥锁

	pthread_cond_init(&cond, NULL); // 初始化条件变量

	pthread_join(p1, NULL); // 销毁两个线程
	pthread_join(p2, NULL);

	pthread_mutex_destroy(&mutex); // 销毁互斥锁

	pthread_cond_destroy(&cond); // 销毁条件变量
	return 0;
}

 结果如下:

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值