linux 线程私有数据

  • Linux线程私有数据(Thread-Specific Data,TSD)是指在多线程程序中,每个线程都可以拥有自己的私有数据,这些数据对于其他线程是不可见的。在Linux中,可以使用线程特定数据(Thread-Specific Data,TSD)来实现线程私有数据。

线程特定数据是一种机制,它允许每个线程都拥有自己的私有数据。在Linux中,可以使用pthread_key_create函数创建线程特定数据键,使用pthread_setspecific函数将数据与键关联起来,使用pthread_getspecific函数获取与键关联的数据。

  • 类似于errno,不是全局变量,因为多个线程同时访问的话可能出现资源同步问题,私有数据是一键对多值,每个线程可以根据同一个key,设置自己的数据,也可以通过key对数据进行获取
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_key_t key;

struct student{
    int id;
    char nm[20];
}student_def;

void child1(void* arg)
{
    struct student stu_tmp;
    memset(&stu_tmp, 0x00, sizeof(student_def));
    stu_tmp.id=10;
    strcpy(stu_tmp.nm, "hello");
    pthread_setspecific(key, (void*)&stu_tmp);
    printf("child1:id=%d, nm=%s\n", ((struct student*)pthread_getspecific(key))->id, 
                        ((struct student*)pthread_getspecific(key))->nm);
}

void child2(void* arg)
{
    struct student stu_tmp;
    memset(&stu_tmp, 0x00, sizeof(student_def));
    stu_tmp.id=20;
    strcpy(stu_tmp.nm, "world");
    pthread_setspecific(key, (void*)&stu_tmp);
    
    printf("child2:id=%d, nm=%s\n", ((struct student*)pthread_getspecific(key))->id, 
                        ((struct student*)pthread_getspecific(key))->nm);
}

int main()
{
    pthread_t ptid1;
    pthread_t ptid2;
    
    pthread_key_create(&key, NULL);
    pthread_create(&ptid1, NULL, (void*)child1, NULL);
    pthread_create(&ptid2, NULL, (void*)child2, NULL);
    
    pthread_join(ptid1, NULL);
    pthread_join(ptid2, NULL);
    pthread_key_delete (key);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值