创建三个线程,分别打印 a,b,c. 现在要求用信号量对线程进行同步,无论程序运行 多少次、如何运行,都能使整个程序依次打印 a b c a b c a b c . . . 一直死循环
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#include<unistd.h>#include<pthread.h>
#include<sys/sem.h>
#include<semaphore.h>
#define MAX 3
sem_t sem1;
sem_t sem2;
sem_t sem3;
void *fun1(void *arg)
{
while(1)
{
sem_wait(&sem1);
printf("a\n");
sem_post(&sem2);
}
}void *fun2(void *arg)
{
while(1)
{
sem_wait(&sem2);
printf("b\n");
sem_post(&sem3);
}
}
void *fun3(void *arg)
{
while(1)
{
sem_wait(&sem3);
printf("c\n");
sem_post(&sem1);
}
}
int main()
{
pthread_t id[MAX];
pthread_create(&id[0],NULL,fun1,NULL);
pthread_create(&id[1],NULL,fun2,NULL);
pthread_create(&id[2],NULL,fun3,NULL);
sem_init(&sem1,0,1);
sem_init(&sem2,0,0);
sem_init(&sem3,0,0);
int i = 0;
for (;i < MAX;i++)
{
pthread_join(id[i],NULL);
}
sem_destroy(&sem1);
sem_destroy(&sem2);
sem_destroy(&sem3);
exit(0);
}
结果如下: