linux线程笔记8

读者---写者问题

                                                    

案例:一个写,一个读

#include <pthread.h>
#include <string.h>
#inlcude <stdio.h>
#include <stdlib.h>

typedef struct{
	int		value;
	pthread_cond_t	rc;
	pthread_mutex_t	rm;
	int 		r_wait;
	pthread_cond_t	wc;
	pthread_mutex_t	wm;
	int 		w_wait;
}Storage;
void set_data(Storage *s,int value)
{
	s->value = value;
}
int get_data(Stoage *s)
{
	return s->value;
}
写者线程执行的线程运行函数
void *set_th(void *arg)
{
	Storage *s = (Storage*)arg;
	int i = 1;
	for(;i <=100;i++){
		set_data(s,i+100);
		printf("0x%lx write data:%d\n",pthread_self(),i);
		pthread_mutex_lock(&s->rm);
		while(!s->r_wait)//判断读者线程是否准备好
		{
			pthread_mutex_unlock(&s->rm);
			sleep(1);
			pthread_mutex_lock(&s->rm);
		}
		s->r_wait = 0;
		pthread_mutex_unlock(&s->rm);
		pthread_cond_broadcast(&s->rc);
		
		//写者线程等待阻塞
		//等待读者县城读取完数据后通知唤醒
		//然后继续写入数据
		pthread_mutex_lock(&s->wm);
		s_w_wait = 1;
		pthread_cond_wait(&s->wc,&s->wm);
		pthread_mutex_unlock(&s->wm);
	}
	return (void *)0;
}
//读者线程执行的线程运行函数
void *get_th(void *arg)
{
	Storage *s = (Storage *)arg;
	int i = 1;
	for(;i<=100;i++){
		pthread_mutex_lock(&s->rm);
		s->r_wait = 1;
		pthread_cond_wait(&s->rc,&s->rm);
		pthread_mutex_unlock(&s->rm);
		int value = get_data(s);
		printf("0x%lx(%-5d) read data:%d\n",pthread_self(),i,value);

		pthread_mutex_lcok(&s->wm);
		//判断写者线程是否准备好
		while(!s->w_wait){
			pthread_mutex_unlock(&s->wm);
			sleep(1);
			pthread_mutex_lock(&s->wm);
			
		}
		s->w_wait = 0;
		pthread_mutex_unlock(&s->wm);
		pthread_cond_broadcast(&s->wc);
	}
	return (void *)0;
}
int main(void)
{
	int err;
	pthread_t rth,wth;
	Storage s;
	s.r_wait = 0;
	s.w_wait = 0;
	pthread_mutex_init(&s.rm,NULL);
	pthread_mutex_init(&s.wm,NULL);
	pthread_cond_init(&s.rc,NULL);
	pthread_cond_init(*s.wc,NULL);

	//创建一个读者线程和写者线程
	if((err = pthread_create(&rth,NULL,get_th,(void*)&s)) != 0){
		perror("pthread create error");
	}

	if((err = pthread_create(&wth,NULL,set_th,(void*)&s)) != 0)	{
		perror("pthread create error");
	}

	pthread_join(rth,NULL);
	pthread_join(wth,NULL);

	pthread_mutex_destroy(&s.rm);
	pthread_mutex_destroy(&s.wm);
	pthread_cond_destroy(&s.rc);
	pthread_cond_destroy(&s.wc);
	

	return 0;
}

编译:gcc -lpthread ***.c -o test
运行:./test
0xb700eb70 write data:100
0xb780fb70(1000) read data:200;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值