天天看点

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

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

//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;
}
           

执行结果:

[[email protected] 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)静态变量,与全局变量相同。

继续阅读