pthread_once 和 pthread_key

来源:互联网 发布:好一点的耳环品牌 知乎 编辑:程序博客网 时间:2024/05/17 23:25
 

一次性初始化

    有时候我们需要对一些posix变量只进行一次初始化,如线程键(我下面会讲到)。如果我们进行多次初始化程序就会出现错误。

    在传统的顺序编程中,一次性初始化经常通过使用布尔变量来管理。控制变量被静态初始化为0,而任何依赖于初始化的代码都能测试该变量。如果变量值仍然为0,则它能实行初始化,然后将变量置为1。以后检查的代码将跳过初始化。

    但是在多线程程序设计中,事情就变的复杂的多。如果多个线程并发地执行初始化序列代码,可能有2个线程发现控制变量为0,并且都实行初始化,而该过程本该仅仅执行一次。

如果我们需要对一个posix变量静态的初始化,可使用的方法是用一个互斥量对该变量的初始话进行控制。但有时候我们需要对该变量进行动态初始化,pthread_once就会方便的多。 

函数原形:

pthread_once_t once_control=PTHREAD_ONCE_INIT;

int pthread_once(pthread_once_t *once_control,void(*init_routine)(void));

参数:

once_control         控制变量

init_routine         初始化函数

返回值:

若成功返回0,若失败返回错误编号。

 类型为pthread_once_t的变量是一个控制变量。控制变量必须使用PTHREAD_ONCE_INIT宏静态地初始化。

pthread_once函数首先检查控制变量,判断是否已经完成初始化,如果完成就简单地返回;否则,pthread_once调用初始化函数,并且记录下初始化被完成。如果在一个线程初始时,另外的线程调用pthread_once,则调用线程等待,直到那个现成完成初始话返回。

下面就是该函数的程序例子: 

#include <pthread.h>

pthread_once_t once=PTHREAD_ONCE_INIT;

pthread_mutex_t mutex; 

void once_init_routine(void) 

{

    int status;

    status=pthread_mutex_init(&mutex,NULL);

    if(status==0)

    printf(“Init success!,My id is %u”,pthread_self());

}

void *child_thread(void *arg)

{

    printf(“I’m child ,My id is %u”,pthread_self());

    pthread_once(&once,once_init_routine);

}

    int main(int argc,char *argv[ ])

{

    pthread_t child_thread_id;

    pthread_create(&child_thread_id,NULL,child_thread,NULL);

    printf(“I’m father,my id is %u”,pthread_self());

    pthread_once(&once_block,once_init_routine);

    pthread_join(child_thread_id,NULL);

}

线程的私有数据

    在进程内的所有线程共享相同的地址空间,任何声明为静态或外部的变量,或在进程堆声明的变量,都可以被进程所有的线程读写。那怎样才能使线程序拥有自己的私有数据呢。

posix提供了一种方法,创建线程键。

函数原形:

int pthread_key_create(pthread_key *key,void(*destructor)(void *));

参数:

key           私有数据键

destructor    清理函数

返回值:

若成功返回0,若失败返回错误编号

   第一个参数为指向一个键值的指针,第二个参数指明了一个destructor函数(清理函数),如果这个参数不为空,那么当每个线程结束时,系统将调用这个函数来释放绑定在这个键上的内存块。这个函数常和函数pthread_once一起使用,为了让这个键只被创建一次。函数pthread_once声明一个初始化函数,第一次调用pthread_once时它执行这个函数,以后的调用将被它忽略。

下面是程序例子: 

#include <pthread.h>

pthread_key_t tsd_key;

pthread_once_t key_once=PTHREAD_ONCE_INIT;

void once_routine(void)

{

int status;

status=pthread_key_create(&tsd_key,NULL);

if(status=0)

    printf(“Key create success! My id is %u/n”,pthread_self());

}

void *child_thread(void *arg)

{

printf(“I’m child,My id is %u/n”,pthread_self());

pthread_once(&key_once,once_routine);

}

int main(int argc,char *argv[ ])

{

pthread_t child_thread_id;

pthread_create(&child_thread_id,NULL,child_thread,NULL);

printf(“I’m father,my id is%u/n”,pthread_self());

pthread_once(&key_once,once_routine);

}

原创粉丝点击