【发布时间】: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