一、什么是私有数据
应用程序设计中有必要提供一种变量,使得多个函数多个线程都可以访问这个变量(看起来是个全局变量),但是线程对这个变量的访问都不会彼此产生影响(貌似不是全局变量哦),但是你需要这样的数据,比如errno。那么这种数据就是线程的私有数据,尽管名字相同,但是每个 线程访问的都是数据的副本。
二、如何创建私有数据
1、在使用私有数据之前,你首先要创建一个与私有数据相关的键,要来获取对私有数据的访问权限 。这个键的类型是pthread_key_t
int pthread_key_create(pthread_key_t *key, void (*destructor)(voi8d*));
2、创建的键放在key指向的内存单元,destructor是与键相关的析构函数。当线程调用pthread_exit
或者使用return返回,析构函数就会被调用。当析构函数调用的时候,它只有一个参数,这个参数是与key关联的那个数据的地址(也就是你的私有数据啦),因此你可以在析构函数中将这个数据销毁。
3、键使用完之后也可以销毁,当键销毁之后,与它关联的数据并没有销毁哦
int pthread_key_delete(pthread_key_t key);
三、如何使用私有数据
有了键之后,你就可以将私有数据和键关联起来,这样就就可以通过键来找到数据。所有的线程都可以访问这个键,但他们可以为键关联不同的数据。(这岂不是一个名字一样,而值却不同的全局变量么)
1、int pthread_setspecific(pthread_key_t key, const void *value);
将私有数据与key关联
2、void *pthread_getspecific(pthread_key_t key);
获取私有数据的地址,如果没有数据与key关联,那么返回空
四、实例
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <iostream>
#include <queue>
#include "include/pthread.h"
#ifndef _WIN64
#pragma comment(lib,".\\lib32\\pthreadVC2.lib")
#else
#pragma comment(lib,".\\lib64\\pthreadVC2.lib")
#endif
/*
应用程序设计中有必要提供一种变量,使得多个函数多个线程都可以访问这个变量(看起来是个全局变量)
,但是线程对这个变量的访问都不会彼此产生影响(貌似不是全局变量哦),但是你需要这样的数据,比如
errno。那么这种数据就是线程的私有数据,尽管名字相同,但是每个
线程访问的都是数据的副本。
1、在使用私有数据之前,你首先要创建一个与私有数据相关的键,要来获取对私有数据的访问权限 。这个键的类型是pthread_key_t
int pthread_key_create(pthread_key_t *key, void (destructor)(voi8d));
2、创建的键放在key指向的内存单元,destructor是与键相关的析构函数。当线程调用pthread_exit或者使用return返回,析构函数就会被调用。
当析构函数调用的时候,它只有一个参数,这个参数是与key关联的那个数据的地址(也就是你的私有数据啦),因此你可以在析构函数中将
这个数据销毁。
3、键使用完之后也可以销毁,当键销毁之后,与它关联的数据并没有销毁哦
int pthread_key_delete(pthread_key_t key);
1、int pthread_setspecific(pthread_key_t key, const void *value);
将私有数据与key关联
2、void *pthread_getspecific(pthread_key_t key);
获取私有数据的地址,如果没有数据与key关联,那么返回空
*/
pthread_key_t key;
void *thread_fun1(void *arg)
{
printf("thread 1 start!\n");
int a = 1;
//将a和key关联
pthread_setspecific(key, (void *)a);
Sleep(2);
printf("thread 1 key->data is %d\n", pthread_getspecific(key));
return (void*)0;
}
void *thread_fun2(void *arg)
{
Sleep(1);
printf("thread 2 start!\n");
int a = 2;
//将a和key关联
pthread_setspecific(key, (void *)a);
printf("thread 2 key->data is %d\n", pthread_getspecific(key));
return (void*)0;
}
int main()
{
pthread_t tid1, tid2;
//创造一个key
pthread_key_create(&key, NULL);
//创造新线程
if (pthread_create(&tid1, NULL, thread_fun1, NULL))
{
printf("create new thread 1 failed\n");
return 0;
}
if (pthread_create(&tid2, NULL, thread_fun2, NULL))
{
printf("create new thread 2 failed\n");
return 0;
}
//等待新线程结束
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_key_delete(key);
return 0;
}