9-7 练习1

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

#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
//设置全局变量
pthread_cond_t cond;
pthread_mutex_t mutex;
int c;
int flag = 0;
void *task1(void *arg)
{
    FILE *fp = fopen("./zuoye.c", "r");
    while (1)
    {
        pthread_mutex_lock(&mutex);
        if (1 == flag)
        {
            pthread_cond_wait(&cond, &mutex);
        }
        c = fgetc(fp);
        flag = 1;
        if (EOF == c)
        {
            fclose(fp);
            pthread_cond_signal(&cond);
            pthread_mutex_unlock(&mutex);
            pthread_exit(NULL);
        }
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
    }
}
void *task2(void *arg)
{
    while (1)
    {
        pthread_mutex_lock(&mutex);
        if (0 == flag)
        {
            pthread_cond_wait(&cond, &mutex);
        }

        if (EOF == c)
        {
            pthread_mutex_unlock(&mutex);
            pthread_exit(NULL);
        }
        printf("%c", c);
        flag = 0;
        fflush(stdout);
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    //初始化锁
    pthread_mutex_init(&mutex, NULL);
    //初始化条件变量
    pthread_cond_init(&cond, NULL);
    //创建线程
    pthread_t tid1, tid2;

    if (pthread_create(&tid1, NULL, task1, NULL) != 0)
    {
        perror("pthread_create\n");
    }

    if (pthread_create(&tid2, NULL, task2, NULL))
    {
        perror("pthread_create\n");
    }
    //阻塞
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    // 销毁
    pthread_mutex_destroy(&mutex);
    // 销毁
    pthread_cond_destroy(&cond);
    return 0;
}