多线程轮流打印BACD

220 阅读1分钟

利用信号量,in C++, Linux

#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
 
sem_t s1,s2,s3,s4;
 
void* fun1(void* arg)
{
	sem_wait(&s2);
	printf("A\n");
	sem_post(&s3);
}
void* fun2(void* arg)
{
	sem_wait(&s1);
	printf("B\n");
	sem_post(&s2);
}
void* fun3(void* arg)
{
	sem_wait(&s3);
	printf("C\n");
	sem_post(&s4);
}
void* fun4(void* arg)
{
	sem_wait(&s4);
	printf("D\n");
	sem_post(&s1);
}
 
int main()
{
	sem_init(&s1,0,1);
	sem_init(&s2,0,0);
	sem_init(&s3,0,0);
	sem_init(&s4,0,0);
 
	pthread_t tid[4];
	pthread_create(tid+0,NULL,fun1,NULL);
	pthread_create(tid+1,NULL,fun2,NULL);
	pthread_create(tid+2,NULL,fun3,NULL);
	pthread_create(tid+3,NULL,fun4,NULL);
	int i=0;
	for(i=0;i<4;i++)
		pthread_join(tid[i],NULL);
	
	sem_destroy(&s1);
	sem_destroy(&s2);
	sem_destroy(&s3);
	sem_destroy(&s4);
}