线程访问变量的本质
#include<stdio.h>#include<unistd.h>
#include<pthread.h>
int a=1;
void* create(void* arg)
{
printf("new thread\n");
printf("a=%d\n",a);
a++;
return (void*)0;
}
int main()
{
pthread_t tidp;
int error;
a=5;
printf("in the main1:a=%d\n",a);
error=pthread_create(&tidp,NULL,create,NULL);
if(error)
{
printf("new thread is not created\n");
return -1;
}
sleep(1);
printf("in the main2:a=%d\n",a);
printf("new thread is created");
return 0;
}
为什么在线程里输出的a=1,在main里面都是a=5,这其中的本质谁能给讲的明白一点,就是关于线程和主函数访问变量的机制,如果把a=1去掉,线程为什么就会报错而不会访问到a=5呢?谢谢大家! 如果把int a=1改为static int a=1呢?求解答 楼主梦游了吗.. 变量的就近原则。 int error;
a=5;
??你确定这样能通过编译?如果是int error, a = 5;那么可以理解为就近原则。代码会在自己的那个作用域中找到相应的变量。准确的说main函数中的a是定义在main自己的栈内的。而最开始的int a;是在数据段中的,属于全局变量,因此线程可以访问。如果设置为static,线程可以访问,但是main中仍然会优先范围自己栈中的a。 回复 5# gulang2004xy
是这样的,谢谢楼上,也谢谢其他大神 复习变量的 live scope
页:
[1]