pthread once詳解和使用

2022-03-21 01:34:53 字數 1406 閱讀 6958

**:pthread_once()函式詳解 、pthread_once()使用

在多執行緒環境中,有些事僅需要執行一次。通常當初始化應用程式時,可以比較容易地將其放在main函式中。但當你寫乙個庫時,就不能在main裡面初始化了,你可以用靜態初始化,但使用一次初始化(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()函式僅執行一次,究竟在哪個執行緒中執行是不定的,是由核心排程來決定。

linux threads使用互斥鎖和條件變數保證由pthread_once()指定的函式執行且僅執行一次,而once_control表示是否執行過。

如果once_control的初值不是pthread_once_init(linux threads定義為0),pthread_once() 的行為就會不正常。

在linuxthreads中,實際"一次性函式"的執行狀態有三種:never(0)、in_progress(1)、done(2),如果once初值設為1,則由於所有pthread_once()都必須等待其中乙個激發"已執行一次"訊號,因此所有pthread_once ()都會陷入永久的等待中;如果設為2,則表示該函式已執行過一次,從而所有pthread_once()都會立即返回0。

具體的乙個例項:

#include#include

using

namespace

std;

pthread_once_t once =pthread_once_init;

void once_run(void

)

void * child1(void *arg)

void * child2(void *arg)

int main(void

)

執行結果:

hello  

thread

3086535584

enter

once_run

in thread 3086535584

thread

3086535584

return

thread

3076045728

enter

thread

3076045728

return

main thread exit

pthread once 函式詳解

在多執行緒環境中,有些事僅需要執行一次。通常當初始化應用程式時,可以比較容易地將其放在main函式中。但當你寫乙個庫時,就不能在main裡面初始化了,你可以用靜態初始化,但使用一次初始化 pthread once 會比較容易些。int pthread once pthread once t once...

pthread once 函式詳解

pthread once 函式詳解 pthread once 函式詳解 在多執行緒環境中,有些事僅需要執行一次。通常當初始化應用程式時,可以比較容易地將其放在main函式中。但當你寫乙個庫時,就不能在main裡面初始化了,你可以用靜態初始化,但使用一次初始化 pthread once 會比較容易些。...

pthread once 函式詳解

在多執行緒環境中,有些事僅需要執行一次。通常當初始化應用程式時,可以比較容易地將其放在main函式中。但當你寫乙個庫時,就不能在main裡面初始化了,你可以用靜態初始化,但使用一次初始化 pthread once 會比較容易些。int pthread once pthread once t once...