线程数据
- 在C语言编程中,我们都知道,数据共享往往是通过全局变量的方式,全局变量在单线程中不会有什么问题,但是在多线程情况下,如果多个线程都对这个全局变量进行读写操作,需要加锁进行保护,锁的代价其实是很大的。
- 在实际的使用中,很多时候我们只想要线程之间的全局变量,只能在该线程内访问,其他线程不能访问,这个时候就可以使用
线程数据
来实现,通过一个键值pthread_key_t
来实现
键值的创建
函数原型:
/* Create a key value identifying a location in the thread-specific
data area. Each thread maintains a distinct thread-specific data
area. DESTR_FUNCTION, if non-NULL, is called with the value
associated to that key when the key is destroyed.
DESTR_FUNCTION is not called if the value associated is NULL when
the key is destroyed. */
extern int pthread_key_create (pthread_key_t *__key,
void (*__destr_function) (void *))
__THROW __nonnull ((1));
第一个参数:就是一个键值的指针
第二个参数:一个destructor
函数,可以传NULL
,如果不为空,当每个线程结束时,调用这个函数来释放绑定在这个键值上的内存快(这个参数很厉害,Demo中有使用说明)。
注:
值得注意的是,这个函数往往和pthread_once()
函数一起使用,目的是让这个键值只被创建一次
/* Guarantee that the initialization function INIT_ROUTINE will be called
only once, even if pthread_once is executed several times with the
same ONCE_CONTROL argument. ONCE_CONTROL must point to a static or
extern variable initialized to PTHREAD_ONCE_INIT.
The initialization functions might throw exception which is why
this function is not marked with __THROW. */
extern int pthread_once (pthread_once_t *__once_control,
void (*__init_routine) (void)) __nonnull ((1, 2));
第一个参数:是和key对应的一个标志,初始化为:PTHREAD_ONCE_INIT
第二个参数:初始化函数
键值的绑定和获取
绑定函数:
/* Store POI