深入Pthread(四):一次初始化-pthread_once_t
来源:互联网 发布:淘宝买钻戒靠谱吗 编辑:程序博客网 时间:2024/04/29 10:07
用到的API:
pthread_once_t once_control = PTHREAD_ONCE_INIT;
int pthread_once(pthread_once_t* once_control, void (*init_routine)(void));
有些事需要一次且仅需要一次执行。通常当初始化应用程序时,可以比较容易地将其放在main函数中。但当你写一个库时,就不能在main里面初始化了,你可以用静态初始化,但使用一次初始化(pthread_once_t)会比较容易些。
例程:
#include <pthread.h>
#include "errors.h"
pthread_once_t once_block = PTHREAD_ONCE_INIT;
pthread_mutex_t mutex;
/*This is the one-time initialization routine. It will be
* called exactly once, no matter how many calls to pthread_once
* with the same control structure are made during the course of
* the program.
*/
void once init routine (void)
{
int status;
status = pthread_mutex_init (&mutex, NULL);
if (status != 0)
err_abort (status, "Init Mutex");
}
/* Thread start routine that calls pthread_once.
*/
void *thread routine (void *arg)
{
int status;
status = pthread_once (&once_block, once_init_routine);
if (status != 0)
err_abort (status, "Once init");
status = pthread_mutex_lock (&mutex);
if (status != 0)
err_abort (status, "Lock mutex");
printf ("thread routine has locked the mutex./n");
status = pthread_mutex_unlock (&mutex);
if (status ! = 0)
err_abort (status, "Unlock mutex");
return NULL;
}
int main (int argc, char *argv[])
{
pthread_t thread_id;
char *input, buffer[64];
int status;
status = pthread_create (&thread_id, NULL, thread_routine, NULL);
if (status != 0)
err_abort (status, "Create thread");
status = pthread_once (&once_block, once_init_routine);
if (status != 0)
err_abort (status, "Once init");
status = pthread_mutex_lock (&mutex);
if (status != 0)
err_abort (status, "Lock mutex");
printf ("Main has locked the mutex./n");
status = pthread_mutex_unlock (&mutex);
if (status != 0)
err_abort (status, "Unlock mutex");
status = pthread_join (thread_id, NULL);
if (status != 0)
err_abort (status, "Join thread");
return 0;
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/future_fighter/archive/2009/02/16/3897183.aspx
- 深入Pthread(四):一次初始化-pthread_once_t
- 深入Pthread(四):一次初始化-pthread_once_t
- 深入Pthread(四):一次初始化-pthread_once_t
- 深入Pthread(四):一次初始化-pthread_once_t
- 一次初始化-pthread_once_t
- 一次初始化-pthread_once_t pthread_once 函数
- 【pthread系列-8】POSIX线程中的“一次初始化”
- Linux Pthread 深入解析
- Linux Pthread 深入解析
- Linux Pthread 深入解析
- Linux Pthread 深入解析
- Linux Pthread 深入解析
- Linux Pthread 深入解析
- 深入Pthread(五):线程属性
- 深入Pthread(五):线程属性
- 深入Pthread(五):线程属性
- 深入Pthread(五):线程属性
- linux: Linux Pthread 深入解析
- 深入Phtread(二):线程的同步-Mutex
- ibatis处理sybase分页的问题(还没有解决)
- 捆绑感染 思路实现
- SQL COLLCATION CONFLICT(排序冲突)
- 深入Phtread(三):线程的同步-Condition Variables
- 深入Pthread(四):一次初始化-pthread_once_t
- 深入Pthread(五):线程属性
- Linux线程技术的概念与技术发展
- PKU JudgeOnline FAQ 中文版
- Linux 常用C函数说明-接口处理篇(中文版)
- 开张大吉
- 某人的解题报告
- .NET : 读取XML文档的处理指令
- 客户资源管理系统