线程的私有空间

线程内部的全局变量
如果需要在一个线程内部的各个函数调用都能访问、但其它线程不能访问的变量,这就需要新的机制来实现,我们称之为Static memory local to a thread (线程局部静态变量),同时也可称之为线程特有数据。

1 pthread_key_create(&key, NULL);//1
2 ...
3 pthread_getspecific(key);//2
4 pthread_setspecific(key, ptr);//3

第一个函数在main函数里运行,它声明了此进程的每个线程都有一块私有空间。
第二个函数在某个线程里运行,能获得本线程私有空间的地址。
第三个函数是向私有空间里赋值。

 

 

多线程私有数据pthread_key_create

(36条消息) 多线程私有数据pthread_key_create_qixiang2013的博客-CSDN博客_pthread_key_create

复制代码
 1 #include <pthread.h>
 2 #include <stdio.h>
 3  
 4 pthread_key_t key;
 5 pthread_t thid1;
 6 pthread_t thid2;
 7  
 8 void* thread2(void* arg)
 9 {
10     printf("thread:%lu is running\n", pthread_self());
11     
12     int key_va = 3 ;
13  
14     pthread_setspecific(key, (void*)&key_va);
15     
16     printf("thread:%lu return %d\n", pthread_self(), *(int*)pthread_getspecific(key));
17 }
18  
19  
20 void* thread1(void* arg)
21 {
22     printf("thread:%lu is running\n", pthread_self());
23     
24     int key_va = 5;
25     
26     pthread_setspecific(key, (void*)&key_va);
27  
28     pthread_create(&thid2, NULL, thread2, NULL);
29  
30     printf("thread:%lu return %d\n", pthread_self(), *(int*)pthread_getspecific(key));
31 }
32  
33  
34 int main()
35 {
36     printf("main thread:%lu is running\n", pthread_self());
37  
38     pthread_key_create(&key, NULL);
39  
40     pthread_create(&thid1, NULL, thread1, NULL);
41  
42     pthread_join(thid1, NULL);
43     pthread_join(thid2, NULL);
44  
45     int key_va = 1;
46     pthread_setspecific(key, (void*)&key_va);
47     
48     printf("thread:%lu return %d\n", pthread_self(), *(int*)pthread_getspecific(key));
49  
50     pthread_key_delete(key);
51         
52     printf("main thread exit\n");
53     return 0;
54 }
复制代码

 

posted @   放弃吧  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示