您的位置:首页 > 其它

pthread_exit ---- 不能使用局部变量作为参数返回

2017-06-27 17:54 253 查看
在使用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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程