函数声明
int pthread_once(pthread_once_t *once_control, void (*init_routine) (void));
功能:本函数使用初值为 PTHREAD_ONCE_INIT 的 once_control 变量保证 init_routine() 函数在本进程执行序列中仅执行一次。
参数:
- once_control 控制变量(为 pthread_once_t * 类型,必须使用 PTHREAD_ONCE_INIT 宏静态地初始化。)
- init_routine 初始化函数
返回值:若成功返回0,若失败返回错误编号。
pthread_once函数首先检查控制变量,判断是否已经完成初始化,如果完成就简单地返回;否则,pthread_once调用初始化函数,并且记录下初始化被完成。如果在一个线程初始时,另外的线程调用pthread_once,则调用线程等待,直到那个现成完成初始话返回。
#include <semaphore.h>
#include <sys/types.h>
#include <dirent.h>
#include <pthread.h>
#include <errno.h>
#include <signal.h>
#include <time.h>
#include <stdio.h>
#include <unistd.h>
pthread_once_t once = PTHREAD_ONCE_INIT;
void once_run(void)
{
int tid = pthread_self();
printf("once_run in thread %u\n", tid);
}
void* task1(void* arg)
{
int tid = pthread_self();
printf("thread1 enter %u\n", tid);
pthread_once(&once, once_run);
printf("thread1 returns %u\n", tid);
return NULL;
}
void* task2(void* arg)
{
int tid = pthread_self();
printf("thread2 enter %u\n", tid);
pthread_once(&once, once_run);
printf("thread2 returns %u\n", tid);
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t thrd1, thrd2;
pthread_create(&thrd1, NULL, (void*)task1, NULL);
pthread_create(&thrd2, NULL, (void*)task2, NULL);
sleep(5);
printf("Main thread exit...\n");
return 0;
}
从以上例子可以看出,虽然 pthread_create 分别创建了task1和task2两个不同的线程,但是由于每个task内部都通过pthread_once函数来调用的once_run(),所以打印语句最终只走一次,而不是两次。运行结果如下:
执行结果:
[root@robot ~]$ gcc -o pthread_once_test_two pthread_once_test_two.c -lpthread
[root@robot ~]$ ./pthread_once_test_two
thread1 enter 1850025728
once_run in thread 1850025728
thread1 returns 1850025728
thread2 enter 1841633024
thread2 returns 1841633024
Main thread exit...
[root@robot ~]$
适用范围
这种情况一般用于某个多线程调用的模块使用前的初始化,但是无法判定哪个线程先运行,从而不知道把初始化代码放在哪个线程合适的问题。
当然,我们一般的做法是把初始化函数放在main里,创建线程之前来完成,但是如果我们的程序最终不是做成可执行程序,而是编译成库的形式,那么main函数这种方式就没法做到了。
在多线程编程环境下,尽管pthread_once()调用会出现在多个线程中,init_routine()函数仅执行一次,究竟在哪个线程中执行是不定的,是由内核调度来决定。
基本原理
Linux Threads 使用互斥锁和条件变量保证由 pthread_once() 指定的函数执行且仅执行一次,而 once_control 则表征是否执行过。如果 once_control 的初值不是PTHREAD_ONCE_INIT(Linux Threads定义为0),pthread_once()的行为就会不正常。在Linux Threads中,实际”一次性函数”的执行状态有三种:NEVER(0)、IN_PROGRESS(1)、DONE(2),如果 once初值设为1,则由于所有 pthread_once() 都必须等待其中一个激发”已执行一次”信号,因此所有pthread_once()都会陷入永久的等待中;如果设为2,则表示该函数已执行过一次,从而所有 pthread_once() 都会立即返回0。
参考: