POSIX的只执行一次的pthread_once


POSIX的只执行一次的pthread_once

  1. #ifdef WIN32   
  2.     #include <windows.h>   
  3.     #define SLEEP(ms)               Sleep(ms)   
  4. #else if defined(LINUX)   
  5.     #include <stdio.h>   
  6.     #define SLEEP(ms) sleep(ms)   
  7. #endif   
  8.   
  9. #include <cassert>   
  10. #include <pthread.h>   
  11.   
  12. // 取出线程的ID   
  13. int GetThreadID()  
  14. {  
  15. #ifdef WIN32   
  16.     return (int)pthread_getw32threadhandle_np( pthread_self() );  
  17. #else if defined(LINUX)   
  18.     return (int)pthread_self();  
  19. #endif   
  20. }  
  21.   
  22. // 该静态变量被所有线程使用   
  23. static int s_nThreadResult = 0;  
  24.   
  25. static pthread_once_t once = PTHREAD_ONCE_INIT;  
  26.   
  27. // 该初始化函数,我在多线程下只想执行一次   
  28. void thread_init()  
  29. {  
  30.     s_nThreadResult = -1;  
  31.     printf("[Child %0.4x] looping i(%0.8x)\n", GetThreadID(), s_nThreadResult);  
  32. }  
  33.   
  34. void * theThread(void * param)  
  35. {  
  36.     // 通过once的控制,thread_init只会被执行一次   
  37.     pthread_once(&once, &thread_init);  
  38.     printf("[Child %0.4x] looping i(%0.8x)\n", GetThreadID(), s_nThreadResult);  
  39.   
  40.     s_nThreadResult ++;  
  41.     pthread_exit(&s_nThreadResult);  
  42.   
  43.     return NULL;  
  44. }  
  45.   
  46. int main(int argc, char* argv[])  
  47. {  
  48.     pthread_t tid1, tid2;  
  49.     pthread_create(&tid1, NULL, &theThread, NULL);  
  50.     pthread_create(&tid2, NULL, &theThread, NULL);  
  51.   
  52.     // 无论是否休眠,两个子线程最终都会被主线程join到   
  53.     // 因为两个子线程都是默认的PTHREAD_CREATE_JOINABLE类型   
  54.     //SLEEP(3);   
  55.   
  56.     void * status = NULL;  
  57.     int rc = pthread_join(tid1, &status);  
  58.     assert(rc == 0 && "pthread_join 1", rc);  
  59.     if (status != PTHREAD_CANCELED && status != NULL)  
  60.     {  
  61.         printf("Returned value from thread: %d\n", *(int *)status);  
  62.     }  
  63.   
  64.     rc = pthread_join(tid2, &status);  
  65.     assert(rc == 0 && "pthread_join 2", rc);  
  66.     if (status != PTHREAD_CANCELED && status != NULL)  
  67.     {  
  68.         printf("Returned value from thread: %d\n", *(int *)status);  
  69.     }  
  70.   
  71.     return 0;  
  72. }  

相关内容