代码改变世界

pthread_once和pthread_key_create的用法演示

2014-09-18 21:24  aa12367  阅读(462)  评论(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;
}