9-7 练习2

发布于:2022-12-25 ⋅ 阅读:(210) ⋅ 点赞:(0)

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>

int flag = 0;
//申请锁
pthread_mutex_t mutex;

//条件变量
pthread_cond_t cond1;
//条件变量
pthread_cond_t cond2;
//条件变量
pthread_cond_t cond3;

void *callA(void *arg)
{
    int i = 0;
    while (1)
    {
        pthread_mutex_lock(&mutex);
        if (0 != flag)
        {
            pthread_cond_wait(&cond1, &mutex);
        }
        i++;
        if (i == 11)
        {
            pthread_cond_signal(&cond2);
            pthread_mutex_unlock(&mutex);
            pthread_exit(&mutex);
        }
        printf("A");
        flag = 1;
        pthread_cond_signal(&cond2);
        pthread_mutex_unlock(&mutex);
    }
    pthread_exit(&mutex);
}
void *callB(void *arg)
{
    int i = 0;
    while (1)
    {
        pthread_mutex_lock(&mutex);
        if (1 != flag)
        {
            pthread_cond_wait(&cond2, &mutex);
        }
        i++;
        if (i == 11)
        {
            pthread_cond_signal(&cond3);
            pthread_mutex_unlock(&mutex);
            pthread_exit(&mutex);
        }
        printf("B");
        flag = 2;
        pthread_cond_signal(&cond3);
        pthread_mutex_unlock(&mutex);
    }
    pthread_exit(&mutex);
}
void *callC(void *arg)
{
    int i = 0;
    while (1)
    {
        pthread_mutex_lock(&mutex);
        if (2 != flag)
        {
            pthread_cond_wait(&cond3, &mutex);
        }
        i++;
        if (i == 11)
        {
            pthread_cond_signal(&cond1);
            pthread_mutex_unlock(&mutex);
            pthread_exit(&mutex);
        }
        printf("C");
        flag = 0;
        pthread_cond_signal(&cond1);
        pthread_mutex_unlock(&mutex);
    }
    pthread_exit(&mutex);
}

int main(int argc, const char *argv[])
{
    //初始化条件变量
    pthread_cond_init(&cond1, NULL);
    //初始化条件变量
    pthread_cond_init(&cond2, NULL);
    //初始化条件变量
    pthread_cond_init(&cond3, NULL);
    // 初始化互斥锁
    pthread_mutex_init(&mutex, NULL);
    //创建线程
    pthread_t tid1, tid2, tid3;
    if (pthread_create(&tid1, NULL, callA, NULL) != 0)
    {
        perror("pthread_create\n");
        return -1;
    }
    if (pthread_create(&tid2, NULL, callB, NULL) != 0)
    {

        perror("pthread_create\n");
        return -1;
    }
    if (pthread_create(&tid3, NULL, callC, NULL) != 0)
    {

        perror("pthread_create\n");
        return -1;
    }
    printf("创建线程成功\n");
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_join(tid3, NULL);
    //销毁互斥锁
    pthread_mutex_destroy(&mutex);
    //销毁条件变量
    pthread_cond_destroy(&cond1);
    pthread_cond_destroy(&cond2);
    pthread_cond_destroy(&cond3);
    return 0;
}