pritnOdd 线程如何能够在下面的程序中继续通过偶数和奇数线程打印自然数?

问题描述 投票:0回答:1

以下程序运行良好。但我的疑问是,两个线程(printEven 和 printOdd)一开始都在等待条件变量上的信号(语句 pthread_cond_wait(&cond, &mutex);),那么 printOdd 如何能够进一步进行,即使 printEven 当时无法发出信号。

我会用简单的方式来说明数字 1 是如何打印的? 谁能帮帮我,我真的被这个问题困扰了很长时间。

#include <stdio.h>

#include <unistd.h>


#include <pthread.h>

pthread_t tid[2];

pthread_mutex_t mutex;

pthread_cond_t cond;

int count = 1; // Shared variable to keep track of the current number to be printed


void* printEven(void* arg) {

    while (count <= 10) {

        pthread_mutex_lock(&mutex);

        while (count % 2 != 0) {

            printf("waiting for cv signal\n");

            pthread_cond_wait(&cond, &mutex);

        }

        printf("Even: %d\n", count++);

        pthread_cond_signal(&cond);

        pthread_mutex_unlock(&mutex);

    }

    pthread_exit(NULL);
}

void* printOdd(void* arg) {
while (count <= 10) {

        pthread_mutex_lock(&mutex);

        while (count % 2 != 1) {

            pthread_cond_wait(&cond, &mutex);

        }

        printf("Odd: %d\n", count++);

        pthread_cond_signal(&cond);

        pthread_mutex_unlock(&mutex);

    }

    pthread_exit(NULL);
}


int main() {

    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);

    pthread_create(&tid[1], NULL, printOdd, NULL);
    sleep(10);
    printf("creating even thread\n ");
    pthread_create(&tid[0], NULL, printEven, NULL);

    pthread_join(tid[0], NULL);
    pthread_join(tid[1], NULL);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    return 0;
}
c linux multithreading posix conditional-variable
1个回答
0
投票

数字 1 被打印出来,因为您正在按照正确的方式使用

pthread_cond_wait
。第一次调用
printOdd
时,
count
等于 1,因此
count%2
等于 1,因此函数 不会 调用
pthread_cond_wait

© www.soinside.com 2019 - 2024. All rights reserved.