pthread_exit ---- 不能使用局部变量作为参数返回
2017-06-27 17:54
253 查看
在使用pthread_exit 返回一个void型指针,该指针指向的数据必须不能是线程内部的局部变量,因为随着线程的退出,局部变量被摧毁,变成不确定的内存内容了。
下面的程序比较了使用线程内部的局部变量和全局变量作为pthread_exit返回指针指向的数据内容。其中全局变量可以返回正确的值,而局部变量设置的值已经不一样了。
编译运行:
其实在编译的时候使用-Wall选项后,已经提示warning:函数返回了一个局部变量的地址。
下面的程序比较了使用线程内部的局部变量和全局变量作为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>
相关文章推荐
- 契约操作不能使用引用对象作为参数,只允许使用基本类型或数据契约
- common lisp 中宏定义时不能使用#'? 形式的函数作为参数
- pthread_exit 参数使用
- php的mysql_prepare不能使用表明一类级作为参数
- Golang中interface{}作为函数参数和函数返回值的使用
- 为什么不能使用成员变量的值作为成员函数的默认参数?
- js 不能直接将 console.log 作为参数使用
- Golang中interface{}作为函数参数和函数返回值的使用
- 切勿使用:指向局部变量的指针作为函数的返回指针!
- Windows程序的模块之间为什么不能使用STL容器作为参数
- c++构造函数不能使用本class对象作为参数
- c#asp.net url 传递中文参数要使用 System.Web.HttpUtility.UrlEncode 而不能使用Server.UrlEncode
- 求人看看这个代码,有关DLL中使用回调函数的问题:回调不能返回正确值
- 使用pthread_cond_timedwait把一个线程作为一个定时器使用.
- c++中临时变量不能作为非const的引用参数
- 使用 struts2.0 返回数据列表时的collection 变量名不能与jsp文件同名?
- (转)SqlHelper 使用中需要注意的一点(带输出、返回参数的存储过程)
- 如何使用带参数的对象作为类成员
- ntext不能作为mssql存储过程的输出参数?
- WebService学习之如何使用实体对象作为参数