以下代码有什么问题?由线程Func 1修改的预期X后跟由线程Func 2修改的X.

时间:2017-08-07 16:43:35

标签: c multithreading pthreads mutex pthread-join

在研究多线程时,我编写了以下代码,但在屏幕上没有观察到输出。我在这做错了什么?我期望输出如下:

X modified by threadFunc 1
X modified by threadFunc 2 

但屏幕上看不到任何内容,程序也不会退出。

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

pthread_mutex_t globalMutex[2];
pthread_cond_t globalCondVar[2];

void *threadFunc1(void *args)
{
   pthread_mutex_lock(&globalMutex[0]);
   pthread_cond_wait(&globalCondVar[0], &globalMutex[0]);
   printf("X modified by threadFunc 1\n");
   pthread_mutex_unlock(&globalMutex[0]);
}

void *threadFunc2(void *args)
{
    pthread_mutex_lock(&globalMutex[1]);
    pthread_cond_wait(&globalCondVar[1], &globalMutex[1]);
    printf("X Modified by threadFunc 2\n");
    pthread_mutex_unlock(&globalMutex[1]);
}

int main()
{
    pthread_t thread[2];

    pthread_mutex_init(&globalMutex[0], NULL);
    pthread_mutex_init(&globalMutex[1], NULL);
    pthread_cond_init(&globalCondVar[0], NULL);
    pthread_cond_init(&globalCondVar[1], NULL);

    pthread_create(&thread[0], NULL, threadFunc1, NULL);
    pthread_create(&thread[1], NULL, threadFunc2, NULL);

    pthread_cond_signal(&globalCondVar[0]);
    pthread_cond_signal(&globalCondVar[1]);

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

    pthread_cond_destroy(&globalCondVar[0]);
    pthread_cond_destroy(&globalCondVar[1]);
    pthread_mutex_destroy(&globalMutex[0]);
    pthread_mutex_destroy(&globalMutex[1]);

    return 0;
}

1 个答案:

答案 0 :(得分:1)

条件变量是不是事件。它们被设计用于受互斥锁保护的实际布尔条件。

   (Init)
   condition = false

   (Signal)
   lock mutex
   condition = true
   signal condvar
   unlock mutex

   (Wait)
   lock mutex
   while not condition:
       wait condvar

这是使用条件变量的标准方法。