#include <stdio.h> #include <pthread.h> pthread_key_t key; pthread_once_t ponce = PTHREAD_ONCE_INIT; void ronce(){ printf("%s ", "ronce"); } void *thread1(){ pthread_setspecific(key, "thread1"); printf("%s ", pthread_getspecific(key)); pthread_once(&ponce, ronce); } void *thread2(){ pthread_setspecific(key, "thread2"); printf("%s ", pthread_getspecific(key)); pthread_once(&ponce, ronce); } int main(){ pthread_key_create(&key, NULL); pthread_t tid1, tid2; pthread_create(&tid1, NULL, thread1, NULL); pthread_create(&tid2, NULL, thread2, NULL); pthread_join(tid1, NULL); pthread_join(tid2, NULL); pthread_key_delete(key); }
关于线程私有数据:http://blog.csdn.net/cywosp/article/details/26469435
关于pthread_once:http://blog.csdn.net/lmh12506/article/details/8452659