线程的私有数据

35 篇文章 0 订阅
/*
 * main.cpp
 *
 *  Created on: Jun 27, 2014
 *      Author: john
 */
#include<string.h>
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
pthread_key_t key;
void* thread_1(void* arg) 
{
    int tsd=5;
    printf("thread1 %u is running\n",pthread_self());
    pthread_setspecific(key,(void*)&tsd);
    printf("thread1 %u ",pthread_self());
    int* a=(int*)pthread_getspecific(key);
    printf("return %d\n",*a);
}

void* thread_2(void* arg)
{
    int tsd=0;
    pthread_t thid2;
    printf("thread2 %u is running\n",pthread_self()) ;
    pthread_setspecific(key,(void*)&tsd);
    pthread_create(&thid2,NULL,thread_1,NULL);
    sleep(5);
    printf("thread2 %u ",pthread_self());
    int* a=(int*)pthread_getspecific(key);
    printf("return %d\n",*a);
}

int main()
{
    pthread_t thid1;
    printf("main thread %u is running \n",pthread_self());
    pthread_key_create(&key,NULL);
    int tsd=0;
    pthread_setspecific(key,(void*)&tsd);
    pthread_create(&thid1,NULL,thread_2,NULL);
    sleep(10);
    pthread_key_delete(key);
    printf("main thread exit\n"); 
}

现在呢,说说,线程的私有数据是采用了一种被称为一键多值的技术,一个键值对应多个数值,访问数据时都是通过键值来访问,好像是对一个变量进行访问,其实是在访问不同的数据,使用线程私有数据的时候首先要为每个线程创建一个相关联的键

这里面用到几个API

#include<pthread.h>

int pthread_key_create(pthread_key_t *key,void(*destr_function)(void*));//创建线程的私有变量

int pthread_setspecific(pthread_key_t key,const void* pointer);//设置线程私有变量的值

void* pthread_getspecific(pthread_key_t key);//获取线程私有变量的值

int pthread_key_delete(pthread_key_t key);//删除线程的私有变量

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

世纪殇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值