操作系统:The Sleeping Teaching Assistant

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

sem_t ta,student;
pthread_mutex_t mutex;
int waiting = 0;

void* teaching(void *value);
void* consulting(void *value);

void* teaching(void *value){
	while(1){
		sem_wait(&student);
		pthread_mutex_lock(&mutex);
		waiting--;
		pthread_mutex_unlock(&mutex);
		printf("ta is teaching\n");
		sleep(5);
		sem_post(&ta);
		printf("ta is sleeping\n");
	}
}
void* consulting(void *value){
	while(1){
		pthread_mutex_lock(&mutex);
		if(waiting<3){
			waiting++;
			pthread_mutex_unlock(&mutex);
			printf("%lu is waiting for ta\n",pthread_self());
			sem_post(&student);
			sem_wait(&ta);
			printf("%lu is consulting the ta\n",pthread_self());
			sleep(5);
			printf("consultiation is over\n");
		}
		else{
			pthread_mutex_unlock(&mutex);
			printf("No more chairs\n");
			printf("%lu is programming\n",pthread_self());
			sleep(3);
		}
	}
}

int main(){
	pthread_t amy,bill,carl,daisy,emma,teacher;

	sem_init(&ta,0,1);
	sem_init(&student,0,0);
	pthread_mutex_init(&mutex,NULL);

	pthread_create(&amy,NULL,consulting,NULL);
	pthread_create(&bill,NULL,consulting,NULL);
	pthread_create(&carl,NULL,consulting,NULL);
	pthread_create(&daisy,NULL,consulting,NULL);
	pthread_create(&emma,NULL,consulting,NULL);
	pthread_create(&teacher,NULL,teaching,NULL);
	
	pthread_join(amy,NULL);
	pthread_join(bill,NULL);
	pthread_join(carl,NULL);
	pthread_join(daisy,NULL);
	pthread_join(emma,NULL);
	pthread_join(teacher,NULL);
	
	return 0;
}

运行结果
在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值