gpt4 book ai didi

c - 下面的代码有什么问题?预期 X 由线程 Func 1 修改,随后 X 由线程 Func 2 修改

转载 作者:行者123 更新时间:2023-11-30 14:55:46 32 4
gpt4 key购买 nike

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

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

最佳答案

条件变量不是事件。它们被设计为与受互斥锁保护的实际 bool 条件一起使用。

   (Init)
condition = false

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

(Wait)
lock mutex
while not condition:
wait condvar

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

关于c - 下面的代码有什么问题?预期 X 由线程 Func 1 修改,随后 X 由线程 Func 2 修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45551869/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com