Linux教程網
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;
- }
Copyright ©
Linux教程網 All Rights Reserved