C语言互斥锁-条件变量实现公共缓存区数据读写


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <error.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>

char buffer[128]; 
int has_data=0;
pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_cond_t cond2;

void read_buf(void)
{
	do
	{
		pthread_mutex_lock(&mutex);//锁定互斥锁
		if(has_data==0)
		{
			/*阻塞线程,等待另外一个线程发送信号,同时为公共数据区解锁*/
			pthread_cond_wait(&cond,&mutex);
		}
		else if(has_data==1)
		{
			printf("the data : %s\n",buffer);
			has_data=0;
			pthread_cond_signal(&cond2);
		}
		pthread_mutex_unlock(&mutex);//打开互斥锁
	}while(strcmp(buffer,"#")!=0);
	pthread_exit(NULL);
}

void write_buf(void)
{
	char input[128];
	do
	{
		pthread_mutex_lock(&mutex);
		if(has_data==0)
		{
			memset(input,'\0',128);
			printf("input data:\t");
			scanf("%s",input);
			sprintf(buffer,"%s",input);
			has_data=1;
			pthread_cond_signal(&cond);//条件改变,唤醒阻塞的线程
		
		}
		else if(has_data==1)
		{
			pthread_cond_wait(&cond2,&mutex);
		}
		pthread_mutex_unlock(&mutex);
	}while(strcmp(input,"#")!=0);
	pthread_exit(NULL);
}
int main(int argc,char **argv)
{
	pthread_t id,id2;
	pthread_cond_init(&cond,NULL);
	pthread_cond_init(&cond2,NULL);
	pthread_mutex_init(&mutex,NULL);
	pthread_create(&id,NULL,(void *)read_buf,NULL);//返回值为0,创建成功
	pthread_create(&id2,NULL,(void *)write_buf,NULL);
	pthread_join(id,NULL);
	pthread_join(id2,NULL);
	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值