请看下面的代码:
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了。