int pthread_setspecific(pthread_key_t key, const void *pointer)
void * pthread_getspecific(pthread_key_t key)
#define PTHREAD_KEY_2NDLEVEL_SIZE 32
#define PTHREAD_KEY_1STLEVEL_SIZE ((PTHREAD_KEYS_MAX + PTHREAD_KEY_2NDLEVEL_SIZE - 1)/PTHREAD_KEY_2NDLEVEL_SIZE)
其中在/usr/include/bits/local_lim.h中定義了PTHREAD_KEYS_MAX爲1024,所以一維數組大小爲32。
而具體存放的位置由key值通過如下計算獲得:
idx1st = key / PTHREAD_KEY_2NDLEVEL_SIZEidx2nd = key % PTHREAD_KEY_2NDLEVEL_SIZE
#i nclude <stdio.h>#i nclude <stdio.h>
#i nclude <pthread.h>
pthread_key_t key;
void echomsg(int t){
printf("destructor excuted in thread %d,param=%dn",pthread_self(),t);
}
void * child1(void *arg){
int tid=pthread_self();
printf("thread %d entern",tid);
pthread_setspecific(key,(void *)tid);
sleep(2);
printf("thread %d returns %dn",tid,pthread_getspecific(key));
sleep(5);
}
void * child2(void *arg){
int tid=pthread_self();
printf("thread %d entern",tid);
pthread_setspecific(key,(void *)tid);
sleep(1);
printf("thread %d returns %dn",tid,pthread_getspecific(key));
sleep(5);
}
int main(void){
int tid1,tid2;
printf("hellon");
pthread_key_create(&key,echomsg);
pthread_create(&tid1,NULL,child1,NULL);
pthread_create(&tid2,NULL,child2,NULL);
sleep(10);
pthread_key_delete(key);
printf("main thread exitn");
return 0;
}
#i nclude <pthread.h>
pthread_key_t key;
void echomsg(int t){
printf("destructor excuted in thread %d,param=%dn",pthread_self(),t);
}
void * child1(void *arg){
int tid=pthread_self();
printf("thread %d entern",tid);
pthread_setspecific(key,(void *)tid);
sleep(2);
printf("thread %d returns %dn",tid,pthread_getspecific(key));
sleep(5);
}
void * child2(void *arg){
int tid=pthread_self();
printf("thread %d entern",tid);
pthread_setspecific(key,(void *)tid);
sleep(1);
printf("thread %d returns %dn",tid,pthread_getspecific(key));
sleep(5);
}
int main(void){
int tid1,tid2;
printf("hellon");
pthread_key_create(&key,echomsg);
pthread_create(&tid1,NULL,child1,NULL);
pthread_create(&tid2,NULL,child2,NULL);
sleep(10);
pthread_key_delete(key);
printf("main thread exitn");
return 0;
}
0javascript
收藏html
Ctrl+Enter 發佈java
發佈git
取消ajax