我写了这个小程序来理解pthread_create和pthread_join,但我不明白为什么变量data
的值在thread_join之后被修改。它在调用pthread函数后打印为0。作为参考传递的变量的值在线程中发生了变化
#include <pthread.h>
#include <stdio.h>
void* compute_prime (void* arg)
{
int n = *((int*) arg);
printf("Argument passed is %d\n",n);
return (void *)n;
}
int main()
{
pthread_t thread;
int data = 5000;
int value=0;
pthread_create (&thread, NULL, &compute_prime, &data);
pthread_join (thread, (void*) &value);
printf("The number is %d and return value is %d.\n", data, value);
return 0;
}
,输出是
Argument passed is 5000
The number is 0 and return value is 5000.
''中pthread_join' value'被设置为线程的返回值。这里,这意味着线程函数返回的'n'的值为 –
@CraigEstey问题是数据变化的原因。我没有看到这段代码改变它,即使在'return(void *)n;'中投了错。可能有代码缺失。 –
'return(void *)n;'返回一个指向局部变量的指针,不是吗? –