linux中的线程本地存储pthread_key_t和pthread_once

来源:互联网 发布:python上使用caffe 编辑:程序博客网 时间:2024/05/16 05:31

Linux中提供了这样一种机制:同一进程的多个线程之间既可以共享某个全局变量,也可以做到每一个线程单独使用它,独立设置、获取它的值,而不影响别的线程的使用。这种机制就是线程本地存储(Thread Local Storage, TLS)。

#include <pthread.h>int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));//返回与特定key值关联的数据。void* pthread_getspecific(pthread_key_t key);//设置key值对应的数据,可以通过pthread_getspecific()函数获取,//仅在当前线程中生效。int pthread_setspecific(pthread_key_t key, const void *value);

在多线程环境中,有些事仅需要执行一次。通常当初始化应用程序时,可以比较容易地将其放在main函数中。但当你写一个库时,就不能在main里面初始化了,你可以用静态初始化,但使用一次初始化(pthread_once)会比较容易些。

pthread_once_t once_control=PTHREAD_ONCE_INIT;`int pthread_once(pthread_once_t *once_control, void (*init_routine) (void));

功能:本函数使用初值为PTHREAD_ONCE_INIT的once_control变量保证init_routine()函数在本进程执行序列中仅执行一次。
在多线程编程环境下,尽管pthread_once()调用会出现在多个线程中,init_routine()函数仅执行一次,究竟在哪个线程中执行是不定的,是由内核调度来决定。

0 0
原创粉丝点击