日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > linux >内容正文

linux

(转载)Linux下pthread_once()函数

發布時間:2025/5/22 linux 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 (转载)Linux下pthread_once()函数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
(轉載)http://bbs.chinaunix.net/thread-836577-1-1.html

僅執行一次的操作
int pthread_once(pthread_once_t *once_control, void (*init_routine) (void))

本函數使用初值為PTHREAD_ONCE_INIT的once_control變量保證init_routine()函數在本進程執行序列中僅執行一次。

#include <semaphore.h> #include <sys/types.h> #include <dirent.h> #include <pthread.h> #include <errno.h> #include <signal.h> #include <time.h>pthread_once_t once = PTHREAD_ONCE_INIT;void once_run(void) {printf("once_run in thread %u\n", pthread_self()); }void* task1(void* arg) {int tid = pthread_self();printf("thread1 enter %u\n", tid);pthread_once(&once, once_run);printf("thread1 returns %u\n", tid);return NULL; }void* task2(void* arg) {int tid = pthread_self();printf("thread2 enter %u\n", tid);pthread_once(&once, once_run);printf("thread2 returns %u\n", tid);return NULL; }int main(int argc, char *argv[]) {pthread_t thrd1, thrd2;pthread_create(&thrd1, NULL, (void*)task1, NULL);pthread_create(&thrd2, NULL, (void*)task2, NULL);sleep(5);printf("Main thread exit...\n");return 0; }

程序輸出:

[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()函數僅執行一次,且究竟在哪個線程中執行是不定的,盡管pthread_once(&once,once_run)出現在兩個線程中。

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。

轉載于:https://www.cnblogs.com/Robotke1/archive/2013/05/02/3053958.html

總結

以上是生活随笔為你收集整理的(转载)Linux下pthread_once()函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。