【问题标题】:What is wrong with the below code ? Expected X modified by thread Func 1 followed by X modified by thread Func 2 [duplicate]下面的代码有什么问题?预期 X 由线程 Func 1 修改,然后是 X 由线程 Func 2 修改 [重复]
【发布时间】:2018-01-15 01:15:40
【问题描述】:

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

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;
}

【问题讨论】:

  • 你可能信号太早了。在 main() 信号之前抛出一个 sleep()。
  • 另外,让线程函数返回一些东西
  • 什么@BjornA。说。稍等一下,或者用信号量替换 condvar。

标签: c multithreading pthreads mutex pthread-join


【解决方案1】:

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

   (Init)
   condition = false

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

   (Wait)
   lock mutex
   while not condition:
       wait condvar

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多