【多线程环境下,变量作用域】

如下程序,说明多线程运行时,局部变量和全局变量在两个线程中的作用域

//cat pthread.c 
#include <stdio.h>
#include <pthread.h>

int num = 1;

void *fun(void *arg)
{
	int i=1;
	pthread_t pthid = pthread_self();
	while(1)
	{
		printf("     pthid = %lu, i = %d,num = %d\n",pthid,i,num);	
		sleep(1);
		//i++;
		i += 1;
		num +=2;
	}
	return NULL;
}

void *fun2(void *arg)
{
	int i=100;
	pthread_t pthid = pthread_self();
	while(1)
	{
		printf("pthid = %lu,i = %d,num = %d\n",pthid,i,num);	
		sleep(1);
		i--;
		num -=1;
	}
	return NULL;
}


int main()
{
	pthread_t tid1,tid2;
	pthread_create(&tid1,NULL,fun,NULL);
	pthread_create(&tid2,NULL,fun,NULL);
	
	printf("tid1 = %lu, tid2 = %lu\n",tid1,tid2);

	while(1)	sleep(1);

	return 0;
}

执行结果:
[root@llz pthread]# ./pthread
tid1 = 3077962608, tid2 = 3067472752
     pthid = 3067472752, i = 1,num = 1
     pthid = 3077962608, i = 1,num = 1
     pthid = 3067472752, i = 2,num = 3
     pthid = 3077962608, i = 2,num = 5
     pthid = 3067472752, i = 3,num = 7

     pthid = 3077962608, i = 3,num = 9

 

多线程环境下,变量的作用范围为:
1)局部变量,只作用于本线程,为线程所私有,不同线程下的相同变量各有一份独立拷贝;

比如上例中变量i,线程1 和 线程2 都回调了函数fun(),i为局部变量,其值在每个线程中递增,不会受另一个线程影响;

 

2)全局变量,作用于整个程序,为所有线程所共享,不同线程下的相同变量是同一份拷贝;

比如上例中,变量num 为全局变量,线程1和线程2 调用函数fun()时,num变量的值,在另一个线程计算结果的基础上进行累加;

 

3)静态变量,与全局变量相同。

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值