转载请说明出处:http://blog.csdn.net/cywosp/article/details/26469435git
#include <pthread.h> // Returns 0 on success, or a positive error number on error int pthread_once (pthread_once_t *once_control, void (*init) (void)); 利用参数once_control的状态,函数pthread_once()能够确保不管有多少个线程调用多少次该函数,也只会执行一次由init所指向的由调用者定义的函数。init所指向的函数没有任何参数,形式以下: void init (void) { // some variables initializtion in here }
另外,参数once_control必须是pthread_once_t类型变量的指针,指向初始化为PTHRAD_ONCE_INIT的静态变量。在C++0x之后提供了相似功能的函数std::call_once (),用法与该函数相似。使用实例请参考https://github.com/ApusApp/Swift/blob/master/swift/base/singleton.hpp实现。github
#include <pthread.h> // Returns 0 on success, or a positive error number on error int pthread_key_create (pthread_key_t *key, void (*destructor)(void *)); // Returns 0 on success, or a positive error number on error int pthread_key_delete (pthread_key_t key); // Returns 0 on success, or a positive error number on error int pthread_setspecific (pthread_key_t key, const void *value); // Returns pointer, or NULL if no thread-specific data is associated with key void *pthread_getspecific (pthread_key_t key);
void Dest (void *value) { // Release storage pointed to by 'value' }
因为系统对每一个进程中pthread_key_t类型的个数是有限制的,因此进程中并不能建立无限个的pthread_key_t变量。Linux中能够经过PTHREAD_KEY_MAX(定义于limits.h文件中)或者系统调用sysconf(_SC_THREAD_KEYS_MAX)来肯定当前系统最多支持多少个键。Linux中默认是1024个键,这对于大多数程序来讲已经足够了。若是一个线程中有多个线程局部存储变量,一般能够将这些变量封装到一个数据结构中,而后使封装后的数据结构与一个线程局部变量相关联,这样就能减小对键值的使用。
参数value的值也能够不是一个指向调用者分配的内存区域,而是任何能够强制转换为void*的变量值,在这种状况下,先前的pthread_key_create()函数应将参数destructor设置为NULL
pthread_key_create()返回的pthread_key_t类型值只是对全局数组的索引,该全局数组标记为pthread_keys,其格式大概以下:![]()
数组的每一个元素都是一个包含两个字段的结构,第一个字段标记该数组元素是否在用,第二个字段用于存放针对此键、线程局部存储变的解构函数的一个副本,即destructor函数。
__thread std::string t_object_1 ("Swift"); // 错误,由于不能调用对象的构造函数 __thread std::string* t_object_2 = new std::string (); // 错误,初始化必须用编译期常量 __thread std::string* t_object_3 = nullptr; // 正确,可是须要手工初始化并销毁对象