线程的私有空间

线程内部的全局变量
如果需要在一个线程内部的各个函数调用都能访问、但其它线程不能访问的变量,这就需要新的机制来实现,我们称之为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 @ 2022-11-21 11:25  放弃吧  阅读(28)  评论(0编辑  收藏  举报