码迷,mamicode.com
首页 > 其他好文 > 详细

pthread_once和pthread_key_create的用法演示

时间:2014-09-18 22:07:44      阅读:454      评论:0      收藏:0      [点我收藏+]

标签:blog   ar   div   sp   log   on   c   amp   ad   

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的用法演示

标签:blog   ar   div   sp   log   on   c   amp   ad   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!