Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1454439
  • 博文数量: 181
  • 博客积分: 3308
  • 博客等级: 中校
  • 技术积分: 2227
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-03 12:03
个人简介

我是zoro

文章分类

全部博文(181)

文章存档

2015年(1)

2013年(35)

2012年(39)

2011年(50)

2010年(56)

分类: LINUX

2010-12-03 21:55:58

   在分配线程私有数据之前,要创建与该数据相关联的key。
       #include
       int pthread_key_create(pthread_key_t *keyp, void (*destructor)(void*));
       返回值:若成功返回0,否则返回错误编码。
   需要注意的是:创建的key存放在keyp指向的内存单元,所以为了方便最好把它定义为一个全局变量。

   key一旦创建,就可以调用pthread_setspecific函数把key和线程私有数据关联起来。可以通过pthread_getspecific函数获得线程私有数据的地址。
       #include
       void *pthread_getspecific(pthread_key_t key);
       返回值:线程私有数据地址,若没有值与key关联则返回NULL。
       int pthread_setspecific(pthread_key_t key, const void *value);
       返回值:若成功返回0,否则返回错误编号。

测试代码:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

pthread_key_t key;

static void free_data(void * arg)
{
    printf("Destruct!");
    free(arg);
}

void str_display(void)
{

    char * str = (char *)pthread_getspecific(key);
    if (str == NULL) {
        printf("getspecific wrong!\n");
        return;
    }

    printf("Thread:%x: %s", (int)pthread_self(), str);

    return;
}

void * thread_handler(void * arg)
{
    int ret;
    int i = (int)arg;
    char * str = (char *)malloc(100);
    if (!str) {
        exit(1);
    }

    sprintf(str, "This is %d\n", i);
    ret = pthread_setspecific(key, (void *)str);
    if (ret) {
        fprintf(stderr, "setspecific:%s\n",
            strerror(ret));
        return NULL;    
    }

    str_display();

    return NULL;
}

int main(void)
{
    int ret, i;
    pthread_t tid[3];
    pthread_attr_t attr;

    ret = pthread_key_create(&key, free_data);
    if (ret) {
        printf("key_create:%s\n", strerror(ret));
        exit(1);
    }
    
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr,
        PTHREAD_CREATE_DETACHED);

    for (i = 0; i < 3; i++) {
        ret = pthread_create(tid+i, &attr, thread_handler,
            (void *)i);
        if (ret) {
            fprintf(stderr, "thread_create:%s\n",
                strerror(ret));
            exit(1);    
        }    
    }

    pthread_attr_destroy(&attr);

    pthread_exit(NULL);
}

运行结果:

./test
Thread:b6820b70: This is 2
Destruct!Thread:b7021b70: This is 1
Destruct!Thread:b7822b70: This is 0

Destruct!


阅读(1912) | 评论(0) | 转发(0) |
0

上一篇:linux下 线程 递归锁

下一篇:异步取消线程

给主人留下些什么吧!~~