Linux C 多线程编程互斥锁与条件变量

Linux C 多线程编程互斥锁与条件变量

 

#include"mylib.h"

#define BUFFER_SIZE		5	//产品库存大小
#define PRODUCT_CNT		30	//产品生产总数

struct product_cons
{
	int buffer[BUFFER_SIZE];//生产产品值
	pthread_mutex_t	lock;	//互斥锁 volatile int
	int readpos,writepos;	//读写位置
	pthread_cond_t notempty;//条件变量
	pthread_cond_t notefull;//非满
}buffer;

void init(struct product_cons *p)
{
	pthread_mutex_init(&p->lock,NULL);//互斥锁
	pthread_cond_init(&p->notempty,NULL);//条件变量
	pthread_cond_init(&p->notefull,NULL);//条件变量
	p->readpos = 0;//读写位置
	p->writepos = 0;
}

void finish(struct product_cons *p)
{
	pthread_mutex_destroy(&p->lock);	 //互斥锁
    pthread_cond_destroy(&p->notempty); //条件变量
	pthread_cond_destroy(&p->notefull); //条件变量
    p->readpos = 0;//读写位置
	p->writepos = 0;
}

//存储一个数据到buffer
void put(struct product_cons *p,int data)//输入产品子函数
{
	pthread_mutex_lock(&p->lock);	
	if((p->writepos+1)%BUFFER_SIZE == p->readpos)
	{
		printf("producer wait for not full\n");
		pthread_cond_wait(&p->notefull,&p->lock);
	}
	p->buffer[p->writepos] = data;
	p->writepos ++;
	if(p->writepos >= BUFFER_SIZE)
		p->writepos = 0;
	pthread_cond_signal(&p->notempty);
	pthread_mutex_unlock(&p->lock);
}

//读,移除一个数据 从Buffer
int get(struct product_cons *p)
{
	int data;
	
	pthread_mutex_lock(&p->lock);
	
	if(p->readpos == p->writepos)
	{
		printf("consumer wait for not empty\n");
		pthread_cond_wait(&p->notempty,&p->lock);
	}
	
	data = p->buffer[p->readpos];
	p->readpos++;
	if(p->readpos >= BUFFER_SIZE)
		p->readpos = 0;
	
	pthread_cond_signal(&p->notefull);
	
	pthread_mutex_unlock(&p->lock);
	
	return data;
}

void *producer(void *data)//子线程,生产
{
	int n;
	for(n = 1; n <= PRODUCT_CNT; n++)
	{
		sleep(1);
		printf("put the %d product...\n",n);
		put(&buffer,n);
		printf("put the %d product success\n",n);
	}
	printf("producer stopped\n");
	return NULL;
}

void *consumer(void *data)
{
	static int cnt = 0;
	int num;
	while(1)
	{
		sleep(2);
		printf("get product...\n");
		num = get(&buffer);
		printf("get the %d product success\n",num);
		if(++cnt == PRODUCT_CNT)
			break;
	}
	printf("consumer stopped\n");
	return NULL;
}

int main(int argc,char * argv[])
{
	pthread_t th_a,th_b;
	void *retval;

	init(&buffer);

	pthread_create(&th_a,NULL,producer,0);
	pthread_create(&th_b,NULL,consumer,0);
	
	pthread_join(th_a,&retval);
	pthread_join(th_b,&retval);
	
	finish(&buffer);
	return 0;
}

实验结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值