Linux 线程私有数据

原理

  • 一键多值,所有线程都通过一个公用的键去访问,但是访问到的是不同的值
  • 对于线程来说其私有数据可以当做全局变量去访问,且其他的变量却访问不到
  • 两个线程对自己的私有数据操作是互相不影响的

相关api

pthread_key_create(创建一个键)
pthread_setspecific(为一个键设置线程私有数据)
pthread_getspecific(从一个键读取线程私有数据)
pthread_key_delete(删除一个键)

示例代码

#include <pthread.h>
#include <unistd.h>
#include <iostream>
using namespace std;

pthread_key_t key;//公用的键值

void echomsg(void * arg)
{
    cout << "Key of pthread " <<pthread_self() << "destructing..."<< endl;
}//键的析构函数

void * fun1(void *arg)//线程1
{
    int a = 10;
    pthread_setspecific(key,&a);//为键值设置私有数据
    cout << "in pthread " << pthread_self() << " value of key " <<(int *)pthread_getspecific(key)<<" is " << *(int *)pthread_getspecific(key) << endl;
    //通过私有线程的地址访问数据
}

void * fun2(void * arg)//线程2
{
    int a = 20;
    pthread_setspecific(key,&a);//为键值设置私有数据
    cout << "in pthread " << pthread_self() << " value of key " <<(int *)pthread_getspecific(key)<<" is " << *(int *)pthread_getspecific(key) << endl;
    //通过私有线程的地址访问数据
}

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;
}

运行结果如下



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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。