多线程4——线程私有数据(linux)

在多线程环境下,每个线程都需要处理自身的私有数据,如:数据库连接、Socket连接等。

Linux下C语言使用了一种被称为一键多值的技术来使线程数据私有化。使用线程私有数据时,首先要为每个线程数据创建一个相关联的键。在各个线程内部,都使用这个公共的键来指代线程数据,但是在不同的线程中,这个键代表的数据是不同的。

示例程序:

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

// 声明一个key,用于关联线程的私有数据
pthread_key_t key;

void *thread2(void *arg)
{
    int tsd = 5;
    printf("thread %ld is running\n", (unsigned long int)pthread_self());
    pthread_setspecific(key, (void *)&tsd);

    int result = *((int *)pthread_getspecific(key));

    printf("thread %ld returns %d\n", pthread_self(), result);
}

void *thread1(void *arg)
{
    int tsd = 1;
    pthread_t thid2;

    printf("thread %ld is running\n", (unsigned long int)pthread_self());

    // 为key赋值,此值只能由本线程使用
    // 为key指定新数据时,必须释放原有数据占据的内存空间
    pthread_setspecific(key, (void *)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

晴光

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

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

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

打赏作者

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

抵扣说明:

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

余额充值