创建三个线程,分别打印 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);
}

结果如下: 

创建三个线程,分别打印 a,b,c.

相关文章:

  • 2022-12-23
  • 2021-12-09
  • 2022-12-23
  • 2021-10-14
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-12
  • 2022-01-26
  • 2019-07-09
  • 2022-12-23
相关资源
相似解决方案