【发布时间】:2014-10-11 02:58:47
【问题描述】:
所以我有两个线程。一个做数学,另一个显示数学结果。有时,结果线程首先运行并显示 0 而不是有效结果。我怎样才能防止这种情况发生?
void *math (void *arg);
void *result(void *arg);
int a;
int main(int argc, char *argv[]) {
pthread_t mathT;
pthread_t resultT;
pthread_create(&mathT, NULL, math, NULL);
pthread_create(&resultT, NULL, result, NULL);
pthread_join(mathT, NULL);
pthread_join(resultT, NULL);
return 0;
}
void *math(void *arg) {
a = 9 + 9;
return NULL;
}
void *result(void *arg) {
printf("%d", a);
return NULL;
}
【问题讨论】:
-
那么有两个线程有什么意义呢?只需一个线程串行调用这两个函数。
-
这不是重点。当然,我可以连续执行此操作,但不行,我必须使用单独的线程。
-
把
pthread_join(mathT)放在pthread_create(resultT)前面。 -
尝试在
math(void*)中创建结果线程?它可以确保结果线程遵循数学线程。
标签: c multithreading posix mutex