Linux 线程私有数据

2020-02-29  本文已影响0人  FakeCSer爱去网吧

原理

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

运行结果如下



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

上一篇 下一篇

猜你喜欢

热点阅读