pthread_key_t
struct TlsInfo { // thread local storage Information
~TlsInfo() {
printf("%d TlsInfo destructor done\n", tid);
}
TlsInfo(unsigned int t) : tid(t) {}
unsigned int tid;
/*other information*/
};
#define gettid() syscall(SYS_gettid)
pthread_key_t pkey;
pthread_once_t ponce;
void pthread_key_destructor(void* arg) {
struct TlsInfo* ptr = (struct TlsInfo*) arg;
delete ptr;
printf("pthread_key_destructor done\n");
}
void pthread_key_create_wrapper() {
pthread_key_create(&pkey, pthread_key_destructor);
}
void* fun(void* arg) { // run several fun simultaneously
pthread_once(&ponce, pthread_key_init_wrapper);
struct TlsInfo* ptr = new TlsInfo(gettid());
pthread_setspecific(pkey, ptr);
/*loop : doing something*/
return NULL;
}
__thread
__thread struct TlsInfo* ptr = NULL;
void* fun(void* arg) { // run several fun simultaneously
printf("ptr supposed to be NULL : ptr = %lld\n", (long long)ptr);
ptr = new TlsInfo(gettid());
cout << ptr->tid << endl;
return NULL;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。