这样的数据结构可由POSIX线程库维护,称为Thread Specific Data,简称TSD。
#ifdef WIN32 #include <windows.h> #define SLEEP(ms) Sleep(ms) #else if defined(LINUX) #include <stdio.h> #define SLEEP(ms) sleep(ms) #endif #include <pthread.h> pthread_key_t key; void echomsg(void * value) { printf("[CHILD THREAD] Destructor excuted, param=%s\n", (char *)value); } void * child1(void *arg) { printf("[CHILD THREAD - 1] Thread enter\n"); pthread_setspecific(key, arg); SLEEP(2); printf("[CHILD THREAD - 1] Thread returns %s\n", (char *)pthread_getspecific(key)); pthread_exit(NULL); return NULL; } void * child2(void *arg) { printf("[CHILD THREAD - 2] Thread enter\n"); pthread_setspecific(key, arg); SLEEP(1); printf("[CHILD THREAD - 2] Thread returns %s\n", (char *)pthread_getspecific(key)); return NULL; } static const char * msg[2] = { "Lazy cat", "Brown dog" }; int main(int argc, char* argv[]) { printf("[MAIN THREAD] Hello\n"); pthread_key_create(&key, echomsg); pthread_t tid1,tid2; pthread_create(&tid1, NULL, child1, (void *)msg[0]); pthread_create(&tid2, NULL, child2, (void *)msg[1]); pthread_join(tid1, NULL); pthread_join(tid2, NULL); pthread_key_delete(key); printf("[MAIN THREAD] Exit\n"); return 0; }
从中也可以看出,TSD的数目有上限:PTHREAD_KEYS_MAX。定义于/usr/include/bits/local_lim.h,一般为1024。
不要在destructor里调用pthread_exit函数。