IO 条件变量 静态库

思维导图

第一题 使用互斥锁或者信号量,实现一个简单的生产者消费者模型 一个线程每秒生产3个苹果,另一个线程每秒消费8个苹果

pthread_mutex_t m;
int a=0;

void* run(void* arg){
	while(1){
		pthread_mutex_lock(&m);
		if(a>=8){
			a-=8;
			printf("消费者消费8个苹果,苹果数量:%d\n",a);
		}
		pthread_mutex_unlock(&m);
        sleep(1);
	}
}

int main(int argc, const char *argv[])
{
	pthread_mutex_init(&m,0);

	pthread_t id;
	pthread_create(&id,0,run,0);
	pthread_detach(id);

	while(1){
		pthread_mutex_lock(&m);
		a+=3;
		printf("生产者生产3个苹果,苹果数量:%d\n",a);
		pthread_mutex_unlock(&m);
		sleep(1);
	}
	return 0;
}

第二题

有一个盘子,盘子里面最多放3个苹果,5个橘子 2个生产者线程,一个每秒放1个苹果,另一个每秒2个橘子 放了苹果就不能放橘子,放了橘子就不能放苹果 2个消费者线程,1号消费者线程每秒消费2个苹果,2号消费者线程,每秒消费3个橘子

pthread_mutex_t m;
pthread_mutex_t n;
pthread_mutex_t x;
pthread_cond_t c1;
pthread_cond_t c2;
pthread_cond_t c3;
pthread_cond_t c4;
int a=0;
int o=0;

void* run1(void* arg){
	while(1){
		pthread_mutex_lock(&m);	
		pthread_cond_wait(&c1,&m);
		a-=2;
		printf("消费者1消耗2个苹果,当前苹果:%d\n",a);
		pthread_mutex_unlock(&m);
		sleep(1);
	}
}
void* run2(void* arg){
	while(1){
		pthread_mutex_lock(&x);
		pthread_mutex_lock(&m);
		pthread_cond_wait(&c2,&m);
		a+=1;
		printf("生产者1放了1个苹果,当前苹果:%d\n",a);
		if(a>=2){
			pthread_cond_signal(&c1);
		}
		pthread_mutex_unlock(&m);
		pthread_mutex_unlock(&x);
		sleep(1);
	}
}

void* run3(void* arg){
	while(1){
		pthread_mutex_lock(&n);
		pthread_cond_wait(&c3,&n);
		o-=3;
		printf("消费者2消耗3个橘子,当前橘子:%d\n",o);
		pthread_mutex_unlock(&n);
		sleep(1);
	}
}

void* run4(void* arg){
	while(1){
		pthread_mutex_lock(&x);
		pthread_mutex_lock(&n);
		pthread_cond_wait(&c4,&n);
		o+=2;
		printf("生产者2放了2个橘子,当前橘子:%d\n",o);
		if(o>=3){
			pthread_cond_signal(&c3);
		}
		pthread_mutex_unlock(&n);
		pthread_mutex_unlock(&x);
		sleep(1);
	}
}

int main(int argc, const char *argv[])
{
	pthread_mutex_init(&m,0);
	pthread_mutex_init(&n,0);
	pthread_mutex_init(&x,0);
	pthread_cond_init(&c1,0);
	pthread_cond_init(&c2,0);
	pthread_cond_init(&c3,0);
	pthread_cond_init(&c4,0);

	pthread_t id1,id2,id3,id4;
	pthread_create(&id1,0,run1,0);
	pthread_create(&id2,0,run2,0);
	pthread_create(&id3,0,run3,0);
	pthread_create(&id4,0,run4,0);
	pthread_detach(id1);
	pthread_detach(id2);
	pthread_detach(id3);
	pthread_detach(id4);

	while(1){
		if(a<=2){
			pthread_cond_signal(&c2);
		}
		if(o<=3){
			pthread_cond_signal(&c4);
		}
	}
	return 0;
}

第三题 将函数封装成静态库,并测试,描述该函数的功能 

功能:将键盘输入的字符转换成ascii码输出

int getch();

int main(int argc, const char *argv[])
{
	int i=getch();
	printf("%d\n",i);
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值