pthread_getspecific和pthread_setspecific使用
摘自:https://www.cnblogs.com/zhoug2020/p/3951352.html
pthread_getpecific和pthread_setspecific实现同一个线程中不同函数间共享数据的一种很好的方式。
1 /* 2 3 * ===================================================================================== 4 5 * Filename: thead.c 6 7 * Description: getspecific 8 9 * Created: 05/10/2011 12:09:43 AM 10 11 * ===================================================================================== 12 13 */ 14 15 #include<stdio.h> 16 17 #include<pthread.h> 18 19 #include<string.h> 20 21 pthread_key_t p_key; 22 23 24 25 void func1() 26 27 { 28 29 int *tmp = (int*)pthread_getspecific(p_key);//同一线程内的各个函数间共享数据。 30 31 printf("%d is runing in %s\n",*tmp,__func__); 32 33 34 35 } 36 37 void *thread_func(void *args) 38 39 { 40 41 42 43 pthread_setspecific(p_key,args); 44 45 46 47 int *tmp = (int*)pthread_getspecific(p_key);//获得线程的私有空间 48 49 printf("%d is runing in %s\n",*tmp,__func__); 50 51 52 53 *tmp = (*tmp)*100;//修改私有变量的值 54 55 56 57 func1(); 58 59 60 61 return (void*)0; 62 63 } 64 65 int main() 66 67 { 68 69 pthread_t pa, pb; 70 71 int a=1; 72 73 int b=2; 74 75 pthread_key_create(&p_key,NULL); 76 77 pthread_create(&pa, NULL,thread_func,&a); 78 79 pthread_create(&pb, NULL,thread_func,&b); 80 81 pthread_join(pa, NULL); 82 83 pthread_join(pb, NULL); 84 85 return 0; 86 87 } 88 89
#gcc -lpthread test.c -o test # ./test 2 is runing in thread_func 1 is runing in thread_func 100 is runing in func1 200 is runing in func1
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)