Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

pthread_once:確保初始化在多執行緒下只跑一次

在多執行緒環境裡,有些初始化工作(例如設定全域狀態)我們只希望它「無論有多少執行緒呼叫,實際只執行一次」。POSIX 提供的 pthread_once 正是為此而生:它保證傳入的初始化函式在整個行程生命週期內只會被執行一次,其餘呼叫都會直接返回。

#ifdef WIN32
    #include <windows.h>
    #define SLEEP(ms)                Sleep(ms)
#else if defined(LINUX)
    #include <stdio.h>
    #define SLEEP(ms) sleep(ms)
#endif

#include <cassert>
#include <pthread.h>

// 取出執行緒的 ID
int GetThreadID()
{
#ifdef WIN32
    return (int)pthread_getw32threadhandle_np( pthread_self() );
#else if defined(LINUX)
    return (int)pthread_self();
#endif
}

// 該靜態變量被所有執行緒使用
static int s_nThreadResult = 0;

static pthread_once_t once = PTHREAD_ONCE_INIT;

// 該初始化函數,我在多執行緒下只想執行一次
void thread_init()
{
    s_nThreadResult = -1;
    printf("[Child %0.4x] looping i(%0.8x)\n", GetThreadID(), s_nThreadResult);
}

void * theThread(void * param)
{
    // 通過 once 的控制,thread_init 只會被執行一次
    pthread_once(&once, &thread_init);
    printf("[Child %0.4x] looping i(%0.8x)\n", GetThreadID(), s_nThreadResult);

    s_nThreadResult ++;
    pthread_exit(&s_nThreadResult);

    return NULL;
}

int main(int argc, char* argv[])
{
    pthread_t tid1, tid2;
    pthread_create(&tid1, NULL, &theThread, NULL);
    pthread_create(&tid2, NULL, &theThread, NULL);

    // 無論是否休眠,兩個子執行緒最終都會被主執行緒 join 到
    // 因為兩個子執行緒都是默認的 PTHREAD_CREATE_JOINABLE 類型
    //SLEEP(3);

    void * status = NULL;
    int rc = pthread_join(tid1, &status);
    assert(rc == 0 && "pthread_join 1", rc);
    if (status != PTHREAD_CANCELED && status != NULL)
    {
        printf("Returned value from thread: %d\n", *(int *)status);
    }

    rc = pthread_join(tid2, &status);
    assert(rc == 0 && "pthread_join 2", rc);
    if (status != PTHREAD_CANCELED && status != NULL)
    {
        printf("Returned value from thread: %d\n", *(int *)status);
    }

    return 0;
}

關鍵在於 static pthread_once_t once = PTHREAD_ONCE_INIT; 這個「一次性開關」,。theThread 每個執行緒進入時都會呼叫 pthread_once(&once, &thread_init),但只有第一個到達的執行緒會真正執行 thread_init,把共享變數 s_nThreadResult 設為 -1;其餘執行緒則略過初始化,直接看到已就緒的狀態。這樣便不必自己刻意的加鎖判斷,就能安全地完成一次性初始化。

Copyright © Linux教程網 All Rights Reserved