bai_jimmy

导航

线程私有数据和pthread_once

#include <stdio.h>
#include <pthread.h>

pthread_key_t key;
pthread_once_t ponce = PTHREAD_ONCE_INIT;

void ronce(){
        printf("%s\n", "ronce");
}

void *thread1(){
        pthread_setspecific(key, "thread1");
        printf("%s\n", pthread_getspecific(key));

        pthread_once(&ponce, ronce);
}

void *thread2(){
        pthread_setspecific(key, "thread2");
        printf("%s\n", 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

 

posted on 2016-05-12 10:48  bai_jimmy  阅读(150)  评论(0编辑  收藏  举报