2024.4.7

 

pthread_mutex_t m1;
pthread_mutex_t m2;
void* func(void* age){
	while(1){
		pthread_mutex_lock(&m2);
		printf("the trainB use 371s through the tunnel\n");
			sleep(0.1);
		pthread_mutex_unlock(&m1);
		pthread_mutex_unlock(&m2);
	}
}

int main(int argc, const char *argv[])
{
	pthread_mutex_init(&m1,NULL);
	pthread_mutex_init(&m2,NULL);
	pthread_t id;
	if(pthread_create(&id,NULL,func,NULL)!=0){
		perror("pthread_create");
		return 1;
	}
	pthread_detach(id);
	while(1){
		pthread_mutex_lock(&m1);
		printf("trainA use 186s through the tunnel\n");
		sleep(0.2);
		pthread_mutex_unlock(&m1);
		pthread_mutex_unlock(&m2);
	}

	return 0;
}
sem_t sem1;
sem_t sem2;
sem_t sem3;
void* func1(void* arg){
	while(1){
		sem_wait(&sem2);
		printf("train 367\n");
		sleep(0.6);
		sem_post(&sem3);
	}
}
void* func2(void* arg){
	while(1){
		sem_wait(&sem3);
		printf("train 789\n");
		sleep(1);
		sem_post(&sem1);
	}

}
int main(int argc, const char *argv[])
{
	pthread_t id1,id2;
	sem_init(&sem1,0,1);
	sem_init(&sem2,0,0);
	sem_init(&sem3,0,0);
	if(pthread_create(&id1,NULL,func1,NULL)!=0){
		perror("pthread_create");
		return 1;
	}
	if(pthread_create(&id2,NULL,func2,NULL)!=0){
		perror("pthread_create");
		return 1;
	}
	pthread_detach(id1);
	pthread_detach(id2);
	while(1){
		sem_wait(&sem1);
		printf("the train run 186\n");
		sleep(0.3);
		sem_post(&sem2);
	}
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值