线程的私有数据

使用线程的私有数据

例:

myprivate_key.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>

//gcc -g myprivate_key.c -o myprivate_key -lpthread

#define ERROR(flag,msg)            \
if(flag)                        \
{                                \
    printf("%d: ",__LINE__);    \
    fflush(stdout);                \
    perror(msg);                \
    exit(errno);                \
}

pthread_key_t key;

void *pthread_func(void *arg)
{
    pthread_setspecific(key, arg);
    sleep(2);
    printf("0x%lx set = %lu, get = %lu\n",
            pthread_self(),
            (unsigned long)arg,
            (unsigned long)pthread_getspecific(key));

    return NULL;
}


#define MAX_THREAD 5

int main(int argc, char *argv[])
{
    int i;
    pthread_t tid[MAX_THREAD];
    pthread_key_create(&key, NULL);

    for(i = 0; i < MAX_THREAD; i++)
    {
        pthread_create(tid + i, NULL, pthread_func, (void *)(long)i);
    }

    for(i = 0; i < MAX_THREAD; i++)
    {
        pthread_join(tid[i], NULL);
    }

    pthread_key_delete(key);

    return 0;
}

编译链接运行, 输出如下:

posted @ 2016-01-20 19:58  zhanglong71  阅读(265)  评论(0编辑  收藏  举报