Linux--线程 共享内存空间

线程_共享内存空间

c 复制代码
//线程_共享内存空间

#include <stdio.h>
#include <pthread.h>

int g_data = 0;



void *func1(void *arg)
{
	printf("t1: %ld thread is create!\n",(unsigned long)pthread_self());
	printf("t1: param is %d \n",*((int *)arg));

	while(1){
		printf("t1: %d\n",g_data++);
		sleep(1);
	}
}

void *func2(void *arg)
{
	printf("t2: %ld thread is create!\n",(unsigned long)pthread_self());
	printf("t2: param is %d \n",*((int *)arg));
	
	while(1){
		printf("t2: %d\n",g_data++);
		sleep(1);
	}
}

int main()
{
	int ret;
	int param = 100;
	pthread_t t1;
	pthread_t t2;
	
	int *pret = NULL;
	
	//创建线程
	ret = pthread_create(&t1,NULL,func1,(void *)&param);//调用func1函数
	if(ret == 0){
		printf("main: create t1 success! \n");
	}
	
	ret = pthread_create(&t2,NULL,func2,(void *)&param);//调用func2函数
	if(ret == 0){
		printf("main: create t2 success! \n");
	}
	
	printf("main: %ld\n",(unsigned long)pthread_self());
	
	while(1){
		printf("main: %d\n",g_data++);
		sleep(1);
	}
	
	//等待
	pthread_join(t1,(void **)&pret);
	pthread_join(t2,(void **)&pret);
	
	return 0;
}

运行结果:

bash 复制代码
main:create t1 success !
main:create t2 success !
main 139811894569664 
main:0
t1:139811811059456 thread is create !
t1:param is 100
t1:1
t2:139811802666752 thread is create !
t2:param is 100
t2:2
main:3
t1:4
t2:5
t1:6
main:7

如果使 t1 = 3时退出,运行结果发现:有的时候能捕获到 t1 == 3,退出线程t1;有的时候捕获不到,t1无法退出。

相关推荐
编码浪子40 分钟前
趣味学RUST基础篇(智能指针_结束)
开发语言·算法·rust
MyCollege199943 分钟前
win10使用ssh访问vmware虚拟机
linux·运维·centos
爱编程的化学家2 小时前
代码随想录算法训练营第六天 - 哈希表2 || 454.四数相加II / 383.赎金信 / 15.三数之和 / 18.四数之和
数据结构·c++·算法·leetcode·双指针·哈希
许怀楠3 小时前
【主页介绍】
linux·c++·贪心算法·visual studio
闲人编程4 小时前
图像去雾算法:从物理模型到深度学习实现
图像处理·人工智能·python·深度学习·算法·计算机视觉·去雾
大聪明-PLUS4 小时前
GCC 对 C 语言的扩展
linux·嵌入式·arm·smarc
咔咔学姐kk4 小时前
大模型微调技术宝典:Transformer架构,从小白到专家
人工智能·深度学习·学习·算法·transformer
haogexiaole6 小时前
Dijkstra 算法
算法
Hello.Reader6 小时前
从零到一上手 Protocol Buffers用 C# 打造可演进的通讯录
java·linux·c#
nmxiaocui6 小时前
openssl升级
linux·运维·服务器