int pthread_once(pthread_once_t *once_control, void (*init_routine) (void))
這個函式使用初值為pthread_once_init的once_control變數保證init_routine()函式在本程序執行序列中僅執行一次。
#include2 #include3
4 pthread_once_t once=pthread_once_init;
5 6 void run(void)
7 10 void *thread1(void)
11 17 void *thread2(void)
18 24 int main()
25 33
執行結果:
linuxthreads使用互斥鎖和條件變數保證由pthread_once()指定的函式執行且僅執行一次,而once_control則表徵是否執 行過。如果once_control的初值不是pthread_once_init(linuxthreads定義為0),pthread_once() 的行為就會不正常。在linuxthreads中,實際"一次性函式"的執行狀態有三種:never(0)、in_progress(1)、done (2),如果once初值設為1,則由於所有pthread_once()都必須等待其中乙個激發"已執行一次"訊號,因此所有pthread_once ()都會陷入永久的等待中;如果設為2,則表示該函式已執行過一次,從而所有pthread_once()都會立即返回0。current thread's id is 3070696304
function run is running in thread 3070696304
thread2 ends
current thread's id is 3079089008
thread1 ends
main thread exit!
pthread once詳解和使用
pthread once 函式詳解 pthread once 使用 在多執行緒環境中,有些事僅需要執行一次。通常當初始化應用程式時,可以比較容易地將其放在main函式中。但當你寫乙個庫時,就不能在main裡面初始化了,你可以用靜態初始化,但使用一次初始化 pthread once 會比較容易些。in...
pthread once與執行緒安全的單例模式
在單例模式的class設計的時候,常常會看到一種寫法 if null return 這個辦法叫做double check locking 縮寫為dcl 在 linux多執行緒服務端 一書中,作者提出dcl已經靠不住,並提出了使用pthread once來實現單例的執行緒安全。include int ...
iOS MBProgressHUD的使用方法
mbprogresshud就是乙個非常好用的第三方庫,可以快速接入載入的介面,下面貼 下面的 包含了各種常用型別的載入 import viewcontroller.h import mbprogresshud.h inte ce viewcontroller property atomic,assi...