首页 > 其他 > 详细

pthread_once和pthread_key_create的用法演示

时间:2014-09-18 22:07:44      阅读:398      评论:0      收藏:0      [点我收藏+]
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 = pthread_getspecific(key);
        if ((data = pthread_getspecific(key)) == NULL)
        {
            assert(0);
        }

        fprintf(stderr, "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的用法演示

原文:http://www.cnblogs.com/jimichen/p/3980107.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!