线程私有数据thread-specific
设计线程私有数据主要基于一下两点需求:
1.
2.
为实现线程私有数据POSIX规定了如下接口:
int pthread_key_create(pthread_这个函数创建一个thread-specific数据的键,
程都是可见的。key对应的value是不透明的对象,
数据.和key绑定的values被由pthread_
期和调用线程相同。
注意:同一个键(key)可以被进程中的所有线程使用,
数据的地址不同。当这个键被创建以后,
系统的线程调度算法使得一些线程可能看见一个键值,
值。这是一种竞争状态,我们可以通过pthread_
原型如下:
int pthread_once(pthread_once_t *once_control,
void (*init_routine)(void));
pthread_once_t once_control = PTHREAD_ONCE_INIT;
其中once_control必须为非局部变量,
操作系统保证每个线程调用pthread_
pthread_once被调用一次.
pthread_key_t key;
pthread_once_t init_done = PTHREAD_ONCE_INIT;
void
thread_init(void)
{
err = pthread_key_create(&key, destructor);
}
int
threadfunc(void *arg)
{
pthread_once(&init_done, thread_init);
...
}
一旦key创建成功,我们可以调用pthread_
pthread_
这两个函数的函数原型如下
void *pthread_getspecific(pthread_
int pthread_setspecific(pthread_