歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> POSIX的只執行一次的pthread_once

POSIX的只執行一次的pthread_once

日期:2017/3/1 11:17:59   编辑:Linux編程

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. #include <cassert>
  9. #include <pthread.h>
  10. // 取出線程的ID
  11. int GetThreadID()
  12. {
  13. #ifdef WIN32
  14. return (int)pthread_getw32threadhandle_np( pthread_self() );
  15. #else if defined(LINUX)
  16. return (int)pthread_self();
  17. #endif
  18. }
  19. // 該靜態變量被所有線程使用
  20. static int s_nThreadResult = 0;
  21. static pthread_once_t once = PTHREAD_ONCE_INIT;
  22. // 該初始化函數,我在多線程下只想執行一次
  23. void thread_init()
  24. {
  25. s_nThreadResult = -1;
  26. printf("[Child %0.4x] looping i(%0.8x)\n", GetThreadID(), s_nThreadResult);
  27. }
  28. void * theThread(void * param)
  29. {
  30. // 通過once的控制,thread_init只會被執行一次
  31. pthread_once(&once, &thread_init);
  32. printf("[Child %0.4x] looping i(%0.8x)\n", GetThreadID(), s_nThreadResult);
  33. s_nThreadResult ++;
  34. pthread_exit(&s_nThreadResult);
  35. return NULL;
  36. }
  37. int main(int argc, char* argv[])
  38. {
  39. pthread_t tid1, tid2;
  40. pthread_create(&tid1, NULL, &theThread, NULL);
  41. pthread_create(&tid2, NULL, &theThread, NULL);
  42. // 無論是否休眠,兩個子線程最終都會被主線程join到
  43. // 因為兩個子線程都是默認的PTHREAD_CREATE_JOINABLE類型
  44. //SLEEP(3);
  45. void * status = NULL;
  46. int rc = pthread_join(tid1, &status);
  47. assert(rc == 0 && "pthread_join 1", rc);
  48. if (status != PTHREAD_CANCELED && status != NULL)
  49. {
  50. printf("Returned value from thread: %d\n", *(int *)status);
  51. }
  52. rc = pthread_join(tid2, &status);
  53. assert(rc == 0 && "pthread_join 2", rc);
  54. if (status != PTHREAD_CANCELED && status != NULL)
  55. {
  56. printf("Returned value from thread: %d\n", *(int *)status);
  57. }
  58. return 0;
  59. }
Copyright © Linux教程網 All Rights Reserved