在使用pthread_exit 返回一個void型指針,該指針指向的數據必須不能是線程內部的局部變量,因爲隨着線程的退出,局部變量被摧毀,變成不確定的內存內容了。
下面的程序比較了使用線程內部的局部變量和全局變量作爲pthread_exit返回指針指向的數據內容。其中全局變量可以返回正確的值,而局部變量設置的值已經不一樣了。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
pthread_t ntid1, ntid2;
int ret_val2;
void *thread_func_1(void *arg)
{
int ret_val1;
ret_val1 = 2;
return ((void*)&ret_val1);
}
void *thread_func_2(void *arg)
{
ret_val2 = 2;
return ((void*)&ret_val2);
}
int main(int argc, char *argv[])
{
int rc;
int *p_ret_val1;
int *p_ret_val2;
rc = pthread_create(&ntid1, NULL, thread_func_1, NULL);
if (rc != 0) {
printf("pthread_create error: %s\n", strerror(errno));
}
rc = pthread_create(&ntid2, NULL, thread_func_2, NULL);
if (rc != 0) {
printf("pthread_create error: %s\n", strerror(errno));
}
pthread_join(ntid1, (void*)&p_ret_val1);
printf("p_ret_val1 = %d\n", *p_ret_val1);
pthread_join(ntid2, (void*)&p_ret_val2);
printf("p_ret_val2 = %d\n", *p_ret_val2);
return 0;
}
編譯運行:
其實在編譯的時候使用-Wall選項後,已經提示warning:函數返回了一個局部變量的地址。
gwwu@hz-dev2.aerohive.com:~/test/thread>gcc -g thread2.c -o thread2 -lpthread -Wall
thread2.c: In function ‘thread_func_1’:
thread2.c:18: warning: function returns address of local variable
gwwu@hz-dev2.aerohive.com:~/test/thread>./thread2
p_ret_val1 = 0
p_ret_val2 = 2
gwwu@hz-dev2.aerohive.com:~/test/thread>