条件变量

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>

// 初始化互斥量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

// 条件变量
pthread_cond_t cond1;

// 资源
int source;

// 生产者
void *producer(void *v)
{
	while(1)
	{
		usleep(100000*(rand()%10+1));
		
		pthread_mutex_lock(&mutex);
		source += 2;

		pthread_mutex_unlock(&mutex);
		
		// 广播
		pthread_cond_broadcast(&cond1);
	}
}

// 消费者
void *customer (void *v)
{
	long num = (long)v;
	
	while(1)
	{
		// 为什么要有循环
		// 因为当线程被唤醒的时候,有可能条件还是不满足的,所以还需要判断一次
		// 1、当等待的时候,会自动解锁
		// 2、当被唤醒的时候,会和其他线程一起抢锁
		usleep(100000*(rand()%10+1));
		
		pthread_mutex_lock(&mutex);
		
		while (source <= 0)
		{
			pthread_cond_wait(&cond1, &mutex);
		}
		
		source--;
		printf ("%ld消费者消费,剩余个数%d\n", num, source);
		
		pthread_mutex_unlock(&mutex);
	}
}

// 生产者与消费者
int main()
{
	srand((unsigned int)time(NULL));
	
	pthread_t thread;
	
	long i;
	
	for (i = 0; i < 4; i++)
	{
		pthread_create(&thread, NULL, customer, (void *)(i+1));
		pthread_detach(thread);
	}
	
	pthread_create(&thread, NULL, producer, NULL);
	pthread_detach(thread);
	
	// pthread_cond_init(pthread_cond_t *cond,const pthread_condattr_t *attr);
	// 条件变量的初始化
	pthread_cond_init(&cond1, NULL);

	pthread_exit(NULL);
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值