使用pthread_create创建线程时,避免将局部变量的地址作为线程函数的参数传递

请看下面的代码:

void *thread_1(void *args)
{
    uint8_t tmp = *(uint8_t *)args;
    printf("args is %d\n", tmp);

    return NULL;
}

void create_a_thread(void)
{
    pthread_t thr;
    uint8_t a = 1;

    int ret = pthread_create(&thr, NULL, thread_1, (void *)&a);
    if ( ret != 0 )
    {
        dzlog_error("thread create failed, errno: %d, errmsg: %s", errno, strerror(errno));
    }
}

void main()
{
	create_a_thread();
}

请思考,上面的代码运行后,线程thread_1输出的值是多少?
按道理说,输出的值应该是创建线程时传递进去的地址中的值,即1,但是实际上很可能不是1。
之所以可能不是1,是因为pthread_create没法保证在函数create_a_thread退出之前,线程函数thread_1已经运行起来了,所以可能线程函数thread_1运行起来的时候,create_a_thread函数已经退出了,由于a只是一个临时变量,函数退出之后值不确定,所以这里很可能就不是1了。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值