1.可以使用一个布尔变量和一个静态初始化的互斥量来编写一次性初始化代码,通常这样做;
2.之所以使用pthread_once,主要原因是原来不能静态的初始化一个互斥量,这样如果要使用一个互斥量,必须调用pthread_mutex_init函数初始化互斥量,并且必须仅仅初始化一次,因此初始化调用应该在一次性初始化代码中完成,pthread_once就解决在多线程环境中使得互斥量和初始化代码都仅仅被初始化一次的问题;
3.函数格式:
pthread_once_t once_control = PTHREAD_ONCE_INIT;
int pthread_once(pthread_once_t *once_control, void (*init_routine)(void));
4.摘自pthread_once用户手册:
The first call to pthread_once() by any thread in a process, with a given once_control, shall call the init_routine with no arguments. Subsequent calls of pthread_once() with the same once_control shall not call the init_routine. On return from pthread_once(), init_routine shall have completed. The once_control parameter shall determine whether the associated initialization routine has been called.
The pthread_once() function is not a cancellation point. However, if init_routine is a cancellation point and is canceled, the effect on once_control
shall be as if pthread_once() was never called.(这一句有待测试)
The constant PTHREAD_ONCE_INIT is defined in the
header.
The behavior of pthread_once() is undefined if once_control has automatic storage duration or is not initialized by PTHREAD_ONCE_INIT.
4.下面的代码可以用于修改做测试:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "../errors.h"
pthread_once_t once_block = PTHREAD_ONCE_INIT;
pthread_mutex_t mutex;
static void once_init_routine(void);
static void *thread_routine(void *arg);
int main(int argc, char **argv)
{
int status;
pthread_t thread_id;
status = pthread_create(&thread_id, NULL, thread_routine, NULL);
if(status != 0){
err_abort(status, "create thread");
}
//sleep(1);
status = pthread_once(&once_block, once_init_routine);
if(status != 0){
err_abort(status, "main pthread_once");
}
status = pthread_mutex_lock(&mutex);
if(status != 0){
err_abort(status, "main mutex lock");
}
printf("main has locked the mutex!\n");
status = pthread_mutex_unlock(&mutex);
if(status != 0){
err_abort(status, "main mutex unlock");
}
status = pthread_join(thread_id, NULL);
if(status != 0){
err_abort(status, "join thread");
}
exit(0);
}
static void once_init_routine(void)
{
int status;
status = pthread_mutex_init(&mutex, NULL);
if(status != 0){
err_abort(status, "init mutex");
}
//printf("********************************\n");
}
static void *thread_routine(void *arg)
{
int status;
status = pthread_once(&once_block, once_init_routine);
if(status != 0){
err_abort(status, "thread pthread_once");
}
status = pthread_mutex_lock(&mutex);
if(status != 0){
err_abort(status, "thread mutex lock");
}
printf("thread has locked the mutex\n");
status = pthread_mutex_unlock(&mutex);
if(status != 0){
err_abort(status, "thread mutex unlcok");
}
}
|
阅读(803) | 评论(0) | 转发(0) |