您的位置:首页 > 其它

旧事之局部变量和全局变量

2010-07-20 16:49 218 查看
局部变量和全局变量

局部变量可以和全局变量重名,并且会覆盖全局变量。在引用全局变量时,有两种方式可以选择:引用头文件的方式和extern关键字。

程序的局部变量存放在堆栈

当中,全局变量存放在静态区

中,动态申请数据存放在

中。

下面看一个具体的列子:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
int run_now = 1;
void *thread_fun(void *arg);
int main()
{

pthread_t a_thread;
void *thread_result=NULL;
int print_count1 = 0;

//int run_now = 1;
/*这里就是局部变量,如果这句不注释的话,程序运行的结果:
1
waiting for thread to finished...
joined,it returned OK!
*/

if(pthread_create(&a_thread,NULL,thread_fun,&run_now)!=0)
{
perror("thread create failed");
exit (1);
}

while(print_count1++ < 20)
{
if(run_now == 1)
{
printf("1");
run_now = 2;
}
else
sleep(1);
}

puts("/nwaiting for thread to finished.../n");
if(pthread_join(a_thread,&thread_result))
{
perror("thread join failed");
exit (1);
}
printf("joined,it returned %s/n",(char *)thread_result);

return 0;
}
void *thread_fun(void *arg)
{
int print_count2 = 0;
while(print_count2++ < 20)
{
if(run_now == 2)
{
printf("2");
run_now = 1;
}
else
sleep(1);

}
pthread_exit("OK!");
}


运行结果:

121212121212121212

waiting for thread to finished...

joined,it returned OK!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐