多线程实现abc按顺序循环打印10次

abc顺序打印是通过信号量实现的

代码如下sem_pthread.c:

#include 
#include 
#include 

static sem_t num1, num2, num3;

void* process1(void *arg)
{
    int i = 0;

    for (i = 0; i < 10; i++)
    {
        sem_wait(&num1);
        printf("a\n");
        sem_post(&num2);
    }
    return NULL;
}

void* process2(void *arg)
{
    int i = 0;

    for (i = 0; i < 10; i++)
    {
        sem_wait(&num2);
        printf("b\n");
        sem_post(&num3);
    }
    return NULL;
}

void* process3(void *arg)
{
    int i = 0;

    for (i = 0; i < 10; i++)
    {
        sem_wait(&num3);
        printf("c\n");
        sem_post(&num1);
    }
    return NULL;
}

int main(int argc, char *argv[])
{
    pthread_t tid1, tid2, tid3;

    sem_init(&num1, 0, 1);
    sem_init(&num2, 0, 0);
    sem_init(&num3, 0, 0);

    pthread_create(&tid1, NULL, &process1, NULL);
    pthread_create(&tid2, NULL, &process2, NULL);
    pthread_create(&tid3, NULL, &process3, NULL);

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_join(tid3, NULL);

    sem_destroy(&num1);
    sem_destroy(&num2);
    sem_destroy(&num3);

    return 0;
}

编译命令:

gcc -g -o sem_pthread sem_pthread.c -lpthread

运行结果:

a
b
c
a
b
c
a
b
c
a
b
c
a
b
c
a
b
c
a
b
c
a
b
c
a
b
c
a
b
c

 

你可能感兴趣的:(linux系统编程)