天天看點

Linux多線程5-1_一次性初始化

一、為什麼要使用一次性初始化

    有些事需要且隻能執行一次(比如互斥量初始化)。通常當初始化應用程式時,可以比較容易地将其放在main函數中。但當你寫一個庫函數時,

    就不能在main裡面初始化了,你可以用靜态初始化,但使用一次初始(pthread_once_t)會比較容易些。

二、如何進行一次性初始化

    1、首先要定義一個pthread_once_t變量,這個變量要用宏PTHREAD_ONCE_INIT初始化。然後建立一個與控制變量相關的初始化函數

    pthread_once_t once_control = PTHREAD_ONCE_INIT;

    void init_routine()

    {

         //初始化互斥量

         //初始化讀寫鎖

         ......

    }

    2、接下來就可以在任何時刻調用pthread_once函數

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

    功能:本函數使用初值為PTHREAD_ONCE_INIT的once_control變量保證init_routine()函數在本程序執行序列中僅執行一次。在多線程程式設計

    環境下,盡管pthread_once()調用會出現在多個線程中,init_routine()函數僅執行一次,究竟在哪個線程中執行是不定的,是由核心排程來決定。

    3、Linux Threads使用互斥鎖和條件變量保證由pthread_once()指定的函數執行且僅執行一次。實際"一次性函數"的執行狀态有三種:

        NEVER(0)、IN_PROGRESS(1)、DONE (2),用once_control來表示pthread_once()的執行狀态:

    1)、如果once_control初值為0,那麼 pthread_once從未執行過,init_routine()函數會執行。

    2)、如果once_control初值設為1,則由于所有pthread_once()都必須等待其中一個激發"已執行一次"信号, 是以所有pthread_once ()都會陷入永久

        的等待中,init_routine()就無法執行

    3)、如果once_control設為2,則表示pthread_once()函數已執行過一次,進而所有pthread_once()都會立即   傳回,init_routine()就沒有機會執行

        當pthread_once函數成功傳回,once_control就會被設定為2

三、手冊

PTHREAD_ONCE(3P)           POSIX Programmer’s Manual          PTHREAD_ONCE(3P)

PROLOG

       This  manual page is part of the POSIX Programmer’s Manual.  The Linux implementation of this interface may differ (con-

       sult the corresponding Linux manual page for details of Linux behavior), or the interface  may  not  be  implemented  on

       Linux.

         //這隻是POSIX的手冊,Linux對這個接口的實作可能不一樣,或者有的根本沒有實作這個接口

NAME

       pthread_once - dynamic package initialization

        //動态初始化

SYNOPSIS

       #include

        //頭檔案

       int pthread_once(pthread_once_t *once_control,

              void (*init_routine)(void));

       pthread_once_t once_control = PTHREAD_ONCE_INIT;

DESCRIPTION

       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 associ-

       ated initialization routine has been called.

        //第一次調用 pthread_once()的線程會調用初始化例程,這個初始化函數沒有參數,當再次調用 pthread_once()的時候,初始化

        //例程将不被調用。當 pthread_once()傳回的時候,初始化例程就會完成,once_control變量将會決定初始化例程是否已經被調用

       The pthread_once() function is not a cancellation point. However, if init_routine is a cancellation point  and  is  can-

       celed, the effect on once_control shall be as if pthread_once() was never called.

        // pthread_once()不是一個取消點。但是初始化例程是一個取消點,如果它被取消,那麼 pthread_once()就好像從未調用過

       The constant PTHREAD_ONCE_INIT is defined in the header.

        //PTHREAD_ONCE_INIT定義在頭檔案pthread.h中

       The  behavior  of  pthread_once()  is  undefined if once_control has automatic storage duration or is not initialized by

       PTHREAD_ONCE_INIT.

        // pthread_once()的行為是未知的,如果once_control沒有被初始化

RETURN VALUE

       Upon successful completion, pthread_once() shall return zero; otherwise, an error number shall be returned  to  indicate

       the error.

        //成功傳回0 ,失敗傳回錯誤碼

ERRORS

       The pthread_once() function may fail if:

        // pthread_once()在以下情況會失敗

       EINVAL If either once_control or init_routine is invalid.

                    //once_control變量或者初始化例程是無效的

       The pthread_once() function shall not return an error code of [EINTR].

        //不會傳回EINTR

四、執行個體

1、一次性初始化的驗證

點選(此處)折疊或打開

/*DATE:            2015-4-15

 *AUTHOR:        DDDDD

 *DESCRIPTION:    一次性初始化

    如果once_control為0,init_routine()就會執行

    pthread_once()成功傳回之後,once_control會變為2

 */

#include "apue.h"

pthread_once_t once = 2;

pthread_t tid;

void thread_init()

{

    printf("I'm in thread 0x%x\n", tid);

}

void *thread_fun1(void *arg)

    tid = pthread_self();

    printf("I'm thread 0x%x\n", tid);

    printf("once is %d\n", once);

    pthread_once(&once, thread_init);

    return NULL;

void *thread_fun2(void *arg)

    sleep(2);

int main()

    pthread_t tid1, tid2;

    int err;

    err = pthread_create(&tid1, NULL, thread_fun1, NULL);

    if(err != 0)

        printf("create new thread 1 failed\n");

        return ;

    err = pthread_create(&tid2, NULL, thread_fun2, NULL);

    pthread_join(tid1, NULL);

    pthread_join(tid2, NULL);

    return 0;

2、将互斥量的初始化,使用pthread_once來實作

/*DATA:            2015-4-20

 *AUTHOR;        WJ

 *DESCRIPTION:    使用多線程對一個隊列進行增加和減少,增加操作是一個線程,删除操作是一個線程

 *    

pthread_mutex_t mutex;

pthread_once_t once = PTHREAD_ONCE_INIT;

struct queue{

    int len;

    int write_pos;

    int read_pos;

    int data[50];

};

//互斥量初始化函數

void mutex_init()

    err = pthread_mutex_init(&mutex, NULL);

    if(err)

        printf("mutex init failed\n");

        return;

//隊列初始化

struct queue *queue_init()

    struct queue *que;

    //申請記憶體

    que = (struct queue *)malloc(sizeof(struct queue));

    if(que ==NULL)

        printf("malloc failed\n");

    //初始化

    que->len = 0;

    que->write_pos = 0;

    que->read_pos = 0;

    return que;

void queue_destroy(struct queue *que)

    //銷毀互斥量和que

    pthread_mutex_destroy(&mutex);

    free(que);

void *queue_add(void *arg)

    //對互斥量進行一次性初始化

    pthread_once(&once, mutex_init);

    struct queue *que = (struct queue *)arg;

    int buf=0;

    while(buf50)

        pthread_mutex_lock(&mutex);

        que->data[que->write_pos] = buf;

        que->write_pos ++;

        que->len ++;

        buf++;

        printf("write data %d to queue\n", que->data[que->write_pos -1]);

        pthread_mutex_unlock(&mutex);

        sleep(1);

void *queue_del(void *arg)

    //    對互斥量進行一次性初始化

    while(1)

        sleep(2);

        buf = que->data[que->read_pos];

        que->read_pos ++;

        if(que->len -- == 0)

        {

            printf("queue is empty\n");

            return;

        }

        printf("read data %d from queue\n", que->data[que->read_pos -1]);

    //隊列初始化

    que = queue_init();

    err = pthread_create(&tid1, NULL, queue_add, (void *)que);

        printf("create add thread failed\n");

        queue_destroy(que);

    err = pthread_create(&tid2, NULL, queue_del, (void *)que);

        printf("create del thread failed\n");

    //等待增加和删除操作完成

    //銷毀

    queue_destroy(que);

繼續閱讀