首页 > 代码库 > pthread_once和pthread_key_create的用法演示
pthread_once和pthread_key_create的用法演示
static pthread_key_t key;static pthread_once_t key_once = PTHREAD_ONCE_INIT;void make_key(){ fprintf(stderr, "make_key\n"); pthread_key_create(&key, NULL);}void* thread_routine(void* user_data){ void *ptr; long num = (long)user_data; pthread_once(&key_once, make_key); if ((ptr = pthread_getspecific(key)) == NULL) { ptr = malloc(4); if (num == 1) { strcpy((char*)ptr, "abc"); } else { strcpy((char*)ptr, "def"); } pthread_setspecific(key, ptr); fprintf(stderr, "thread %ld call pthread_setspecific\n", num); } while (1) { void* data = http://www.mamicode.com/pthread_getspecific(key);"thread %ld running %s\n", num, (char*)data); sleep(3); } return NULL;}int main(){ pthread_t t1; pthread_t t2; int r1, r2; r1 = pthread_create(&t1, NULL, thread_routine, (void*)1); r2 = pthread_create(&t2, NULL, thread_routine, (void*)2); assert(r1 == 0 && r2 == 0); pthread_join(t1, NULL); pthread_join(t2, NULL); return 0;}
pthread_once和pthread_key_create的用法演示
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。