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

在使用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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值