zoukankan      html  css  js  c++  java
  • 深入Pthread(四):一次初始化pthread_once_t

    深入Pthread(四):一次初始化-pthread_once_t

     

    用到的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;
    }
     
     
     
      
     
  • 相关阅读:
    thinkphp配置加载
    thinkphp数据输出
    thinkphp 命名规范
    array_fill — 用给定的值填充数组
    array_fill_keys — 使用指定的键和值填充数组
    array_change_key_case — 将数组中的所有键名修改为全大写或小写
    HTMLCSS样式表
    MySql查询语句中的变量使用
    使用java8的方法引用替换硬编码
    如何搭建一个自己的网站(绝对详细~)
  • 原文地址:https://www.cnblogs.com/mywolrd/p/1930699.html
Copyright © 2011-2022 走看看