linux线程高级属性之私有数据

应用程序设计中有必要提供一种变量,使得多个函数多个线程都可以访问这个变量,但是线程对这个变量的访问都不会彼此产生影响。这种数据就是线程的私有数据,尽管名字相同,但是每个线程访问的都是数据的副本。

如何创建私有数据

1、在使用私有数据之前,你首先要创建一个与私有数据相关的,用来获取对私有数据的访问权限 。

int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));

创建的键放在key指向的内存单元,destructor是与键相关的析构函数。当线程调用pthread_exit或者使用return返回,析构函数就会被调用。
2、 当析构函数调用的时候,它只有一个参数,这个参数是与key关联的那个数据的地址(也就是私有数据)

3、可以在析构函数中对这个数据销毁。键使用完之后也可以销毁,当键销毁之后,与它关联的数据并没有销毁

int pthread_key_delete(pthread_key_t key);

使用私有数据

// 将私有数据与key关联
int pthread_setspecific(pthread_key_t key, const void *value);
// 获取私有数据的地址        
void *pthread_getspecific(pthread_key_t key);

实例1:

#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
pthread_key_t key;//1、定义键
void * thread_1(void *arg)
{
	int a = 10;
	printf("I am thread1\n");
	pthread_setspecific(key,(void *)(&a));
	sleep(2);
	printf("key->a = %d\n",*(int *)pthread_getspecific(key));
	return (void *)1;
}
void * thread_2(void *arg)
{
	int a = 20;
	printf("I am thread2\n");
	pthread_setspecific(key,(void *)(&a));//3、将私有数据与key关联
	//4、获取私有数据地址
	printf("key->a = %d\n",*(int *)pthread_getspecific(key));
	return (void *)2;
}
int main(int argc,char *argv[])
{
	pthread_t ntid1,ntid2;
	int err1,err2;
        pthread_key_create(&key,NULL);//2、创建私有数据
	err1 = pthread_create(&ntid1,NULL,thread_1,NULL);
	err2 = pthread_create(&ntid2,NULL,thread_2,NULL);
	if(err1||err2)
	{
		printf("Creat new thread fail\n");
		return -1;
	}
	printf("Creat new thread success\n");
	pthread_join(ntid1,NULL);
    pthread_join(ntid2,NULL);
	pthread_key_delete(key);//5、销毁键
	return 0;
}
运行结果:
binge@binge-HP-Compaq:~/my_share/pthread$ ./a.out
Creat new thread success
I am thread1
I am thread2
key->a = 20
key->a = 10

猜你喜欢

转载自blog.csdn.net/weixin_42039602/article/details/83244367