Linux下 线程之间数据 共享性 分析

   先说下结论:同一个进程下,各个线程之间的数据是共享的,数据的种类可以有很多种,比如标准数据、结构体、文件描述符等等,但是这里有个前提,这些能够被共享的数据,一定是主线程在创建 子线程时,向 子线程传递的数据(通过指针传递)。

程序案例如下:

#include "xxx.h"     //各种必要头文件


void *cthread(void *arg)
{
	int *p = (int *)arg;
	
	pthread_detach(pthread_self());
	while(1){
	
	//  可以直接使用 主线程传递的数据  main_thread_para
	
		printf("main_thread_para:%d\n", *p);
		sleep(1);
	}
}



int main(void *arg)
{
	pthread_t tid;
	
	int main_thread_para;
	
	pthread_create(&tid, NULL, cthread, (void *)&main_thread_para);

	while(1){
		main_thread_para++;
		sleep(1);
	}
}

  程序运行后,我们可以发现,线程中打印的数值 *p 会 递增。说明线程之间的数据是共享的,但是如果在子线程中创建变量,主线程是无法使用的,当然了,如果是全局变量,两个线程都可以使用。

发布了247 篇原创文章 · 获赞 257 · 访问量 62万+

猜你喜欢

转载自blog.csdn.net/u012351051/article/details/97176156
今日推荐