首页 > 编程语言 > 详细

线程的私有数据

时间:2016-01-20 20:56:22      阅读:138      评论:0      收藏:0      [点我收藏+]

使用线程的私有数据

例:

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

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

技术分享

线程的私有数据

原文:http://www.cnblogs.com/zhanglong71/p/5140518.html

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