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

rqqzpn5f  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(84)

下面的程序工作正常。但我的疑问是一开始两个线程(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;
}

字符串

lymnna71

lymnna711#

数字1被打印出来是因为你正在以正确的方式使用pthread_cond_wait。当printOdd第一次被调用时,count等于1,所以count%2等于1,所以函数 * 不 * 调用pthread_cond_wait。
通常,使用pthread_cond_wait的正确方法是,

pthread_mutex_lock(&mutex);
    while (theNecessaryConditionIsNotYetMet()) {
        pthread_mutex_wait(&cond, &mutex);
    }
    doSomethingThatRequiresTheConditionToBeMet();
    pthread_mutex_unlock(&mutex);

字符串
而且,锁定互斥锁的全部意义在于,除非互斥锁被锁定,否则任何线程都不应改变条件是否满足。

相关问题