我寫了這個小程序來理解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;'返回一個指向局部變量的指針,不是嗎? –