(转载)Linux下pthread_once()函数
僅執(zhí)行一次的操作
int pthread_once(pthread_once_t *once_control, void (*init_routine) (void))
本函數(shù)使用初值為PTHREAD_ONCE_INIT的once_control變量保證init_routine()函數(shù)在本進(jìn)程執(zhí)行序列中僅執(zhí)行一次。
程序輸出:
[root@robot ~]# ./thread_once thread2 enter 3067722608 once_run in thread 3067722608 thread2 returns 3067722608 thread1 enter 3078212464 thread1 returns 3078212464 Main thread exit... [root@robot ~]#once_run()函數(shù)僅執(zhí)行一次,且究竟在哪個線程中執(zhí)行是不定的,盡管pthread_once(&once,once_run)出現(xiàn)在兩個線程中。
LinuxThreads 使用互斥鎖和條件變量保證由pthread_once()指定的函數(shù)執(zhí)行且僅執(zhí)行一次,而once_control則表征是否執(zhí)行過。如果 once_control的初值不是PTHREAD_ONCE_INIT(LinuxThreads定義為0),pthread_once()的行為就會不正常。在LinuxThreads中,實(shí)際"一次性函數(shù)"的執(zhí)行狀態(tài)有三種:NEVER(0)、IN_PROGRESS(1)、DONE(2),如果 once初值設(shè)為1,則由于所有pthread_once()都必須等待其中一個激發(fā)"已執(zhí)行一次"信號,因此所有pthread_once()都會陷入永久的等待中;如果設(shè)為2,則表示該函數(shù)已執(zhí)行過一次,從而所有pthread_once()都會立即返回0。
轉(zhuǎn)載于:https://www.cnblogs.com/Robotke1/archive/2013/05/02/3053958.html
總結(jié)
以上是生活随笔為你收集整理的(转载)Linux下pthread_once()函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: latex测试
- 下一篇: 输入对话框基于PyQt4的输入对话框