连续输出ABCABC......(使用线程和信号量实现)

#include 
#include 
#include 
#include 
#include 
#include 

sem_t sema;
sem_t semb;
sem_t semc;
void *funa(void *arg)
{
    for (int i = 0; i < 5; i++)
    {
        sem_wait(&sema);//p
        printf("A");
        fflush(stdout);
        sem_post(&semb);//v
    }
}
void *funb(void *arg)
{
    for (int i = 0; i < 5; i++)
    {
        sem_wait(&semb);
        printf("B");
        fflush(stdout);
        sem_post(&semc);
    }
}
void *func(void *arg)
{
    for (int i = 0; i < 5; i++)
    {
        sem_wait(&semc);
        printf("C");
        fflush(stdout);
        sem_post(&sema);
    }
}
int main()
{
    sem_init(&sema, 0, 1);
    sem_init(&semb, 0, 0);
    sem_init(&semc, 0, 0); //

    pthread_t id1, id2, id3;
    pthread_create(&id1, NULL, funa, NULL);
    pthread_create(&id2, NULL, funb, NULL);
    pthread_create(&id3, NULL, func, NULL);

    pthread_join(id1, NULL);
    pthread_join(id2, NULL);
    pthread_join(id3, NULL);

    sem_destroy(&sema);
    sem_destroy(&sema);
    sem_destroy(&sema);

    exit(0);
}

你可能感兴趣的:(linux,信号处理)