linux 线程 私有数据,Linux 线程私有数据

原理

一键多值,所有线程都通过一个公用的键去访问,但是访问到的是不同的值

对于线程来说其私有数据可以当做全局变量去访问,且其他的变量却访问不到

两个线程对自己的私有数据操作是互相不影响的

相关api

pthread_key_create(创建一个键)

pthread_setspecific(为一个键设置线程私有数据)

pthread_getspecific(从一个键读取线程私有数据)

pthread_key_delete(删除一个键)

示例代码

#include

#include

#include

using namespace std;

pthread_key_t key;//公用的键值

void echomsg(void * arg)

{

cout << "Key of pthread " <

}//键的析构函数

void * fun1(void *arg)//线程1

{

int a = 10;

pthread_setspecific(key,&a);//为键值设置私有数据

cout << "in pthread " << pthread_self() << " value of key " <

//通过私有线程的地址访问数据

}

void * fun2(void * arg)//线程2

{

int a = 20;

pthread_setspecific(key,&a);//为键值设置私有数据

cout << "in pthread " << pthread_self() << " value of key " <

//通过私有线程的地址访问数据

}

int main()

{

pthread_t thread1,thread2;

if(pthread_key_create(&key,echomsg)!=0)//创建一个键值

{

perror("key_create");

exit(1);

}

pthread_create(&thread1,NULL,fun1,NULL);

pthread_create(&thread2,NULL,fun2,NULL);

pthread_join(thread1,NULL);

pthread_join(thread2,NULL);

pthread_key_delete(key);

return 0;

}

运行结果如下

0cefbff22fc2

可见键值相同,但是不是一个地址空间

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值