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 = 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;
}

  

转载于:https://www.cnblogs.com/jimichen/p/3980107.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值