Linux 下C语言多线程编程--线程数据

线程数据

  • 在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
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值