threads 2-局部变量和全局变量

本文探讨了在C语言中如何实现不同线程间的变量共享与通信。通过实例演示了使用全局变量进行通信的方法,并介绍了如何利用pthread_create函数的参数特性实现主线程与子线程之间的数据交换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

main里面定义的变量都是属于主线程的
主线程创建的子线程不能访问之
需用全局变量进行线程间通信
[root@localhost ch12]# cat test4.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

void* thread_function(void *arg);
void *thread_result;

char *str="hello";
int flag=0;
int main()
{
puts(str);
int res;
pthread_t a_thread;
res=pthread_create(&a_thread,NULL,&thread_function,NULL);
if(res!=0){
	perror("pthread_create error");
	exit(EXIT_FAILURE);		
	}
printf("already create a thread\n");

res = pthread_join(a_thread, &thread_result);
puts(str);
}

void* thread_function(void *arg)
{
str="hi";
puts(str);
pthread_exit("thanks");
}

[root@localhost ch12]# 
[root@localhost ch12]# make test4
cc -D_REENTRANT  -lpthread  test4.c   -o test4
[root@localhost ch12]# ./test4
hello
already create a thread
hi
hi
如果将line 11 ,char *str="hello";放到main里面
则编译不会通过
[root@localhost ch12]# make test4
cc -D_REENTRANT  -lpthread  test4.c   -o test4
test4.c: In function ‘thread_function’:
test4.c:31:1: error: ‘str’ undeclared (first use in this function)
test4.c:31:1: note: each undeclared identifier is reported only once for each function it appears in
make: *** [test4] Error 1
局部变量虽然不可以如此明目张胆的通信---被编译器揪出来le
但可冒充pthread_create的参数来进行父子线程的数据交换,如下
[root@localhost ch12]# cat test4.c 
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

void* thread_function(void *arg);
void *thread_result;


int flag=0;
int main()
{
char str[]="hello";
puts(str);
int res;
pthread_t a_thread;
res=pthread_create(&a_thread,NULL,&thread_function,str);
if(res!=0){
	perror("pthread_create error");
	exit(EXIT_FAILURE);		
	}
printf("already create a thread\n");

res = pthread_join(a_thread, &thread_result);
puts(str);
}

void* thread_function(void *arg)
{
strcpy(arg, "hi");
puts(arg);
pthread_exit("thanks");
}

[root@localhost ch12]# make test4
cc -D_REENTRANT  -lpthread  test4.c   -o test4
[root@localhost ch12]# ./test4
hello
already create a thread
hi
hi
定义主线程的局部变量str,充当pthread_create的参数传递给子线程,传的是地址
,以至于在子线程中修改了str,主线程中也可得知
也可单向传递,主线程-->子线程,即传值,如下
[root@localhost ch12]# cat test4.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

void* thread_function(void *arg);
void *thread_result;


int flag=0;
int main()
{
char *str="hello";
puts(str);
int res;
pthread_t a_thread;
res=pthread_create(&a_thread,NULL,&thread_function,str);
if(res!=0){
	perror("pthread_create error");
	exit(EXIT_FAILURE);		
	}
printf("already create a thread\n");

res = pthread_join(a_thread, &thread_result);
puts(str);
}

void* thread_function(void *arg)
{
arg="hi";
puts(arg);
pthread_exit("thanks");
}

[root@localhost ch12]# make test4
cc -D_REENTRANT  -lpthread  test4.c   -o test4
[root@localhost ch12]# ./test4
hello
already create a thread
hi
hello
可见在主线程中第二次打印的str仍然是hello
下面是pthread_create的原型
[root@localhost ch12]# man 3 pthread_create
       #include <pthread.h>

       int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);



### C语言中更新全局变量的方法 在C语言中,更新全局变量的方式主要依赖于作用域规则正确引用全局变量的机制。以下是几种常见方法及其注意事项: #### 1. 直接修改全局变量 全局变量在整个文件或项目范围内都可访问,因此可以直接通过赋值操作更新其值。例如: ```c #include <stdio.h> int globalVar = 0; // 定义全局变量 void updateGlobalVar() { globalVar = 10; // 直接修改全局变量 } int main() { updateGlobalVar(); printf("Updated globalVar: %d\n", globalVar); // 输出 10 return 0; } ``` 需要注意的是,如果局部变量全局变量同名,则局部变量会隐藏全局变量[^1]。 #### 2. 使用`extern`关键字跨文件访问并更新全局变量全局变量定义在一个源文件中,但需要在另一个源文件中更新时,可以使用`extern`关键字声明该变量。例如: **file1.c** ```c #include <stdio.h> int globalVar = 0; // 定义全局变量 void updateGlobalVar(int value) { globalVar = value; // 更新全局变量 } ``` **file2.c** ```c #include <stdio.h> extern int globalVar; // 声明全局变量 int main() { globalVar = 5; // 跨文件更新全局变量 printf("Updated globalVar in file2: %d\n", globalVar); return 0; } ``` 此方法允许不同文件共享更新同一个全局变量,但需确保变量名唯一以避免冲突[^2]。 #### 3. 使用`static`限定全局变量的作用域 若希望限制全局变量仅在其定义的文件内可见,可以使用`static`关键字。这种情况下,其他文件即使使用`extern`也无法访问变量。例如: ```c static int fileScopedVar = 0; // 定义文件范围内的全局变量 void updateFileScopedVar() { fileScopedVar = 10; // 修改文件范围内的全局变量 } ``` 这种方式有助于减少命名冲突提高代码模块化程度[^3]。 #### 4. 注意线程安全问题 在多线程环境中,多个线程可能同时访问修改同一个全局变量,这会导致竞争条件(race condition)。为避免此类问题,应使用互斥锁(mutex)或其他同步机制保护对全局变量访问。例如: ```c #include <pthread.h> #include <stdio.h> int globalVar = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* threadFunc(void* arg) { pthread_mutex_lock(&mutex); // 加锁 globalVar += 1; // 安全地更新全局变量 pthread_mutex_unlock(&mutex); // 解锁 return NULL; } int main() { pthread_t threads[2]; for (int i = 0; i < 2; ++i) { pthread_create(&threads[i], NULL, threadFunc, NULL); } for (int i = 0; i < 2; ++i) { pthread_join(threads[i], NULL); } printf("Final globalVar: %d\n", globalVar); // 输出 2 return 0; } ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值