歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> POSIX的pthread_join

POSIX的pthread_join

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

join

  • join是三種同步線程的方式之一。另外兩種分別是互斥鎖(mutex)和條件變量(condition variable)。
  • 調用pthread_join()將阻塞自己,一直到要等待加入的線程運行結束。
  • 可以用pthread_join()獲取線程的返回值。
  • 一個線程對應一個pthread_join()調用,對同一個線程進行多次pthread_join()調用是邏輯錯誤。

join or detach

  • 線程分兩種:一種可以join,另一種不可以。該屬性在創建線程的時候指定。
  • joinable線程可在創建後,用pthread_detach()顯式地分離。但分離後不可以再合並。該操作不可逆。
  • 為了確保移植性,在創建線程時,最好顯式指定其join或detach屬性。似乎不是所有POSIX實現都是用joinable作默認。
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #define NUM_THREADS 4
  5. void *BusyWork(void *t)
  6. {
  7. double result=0.0;
  8. long tid = (long)t;
  9. printf("Thread %ld starting...\n",tid);
  10. for (int i=0; i<1000000; i++)
  11. {
  12. result = result + sin(i) * tan(i);
  13. }
  14. printf("Thread %ld done. Result = %e\n",tid, result);
  15. pthread_exit((void*) t);
  16. }
  17. int main (int argc, char *argv[])
  18. {
  19. pthread_t thread[NUM_THREADS];
  20. pthread_attr_t attr;
  21. // 1/4: init
  22. pthread_attr_init(&attr);
  23. // 2/4: explicitly specify as joinable or detached
  24. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  25. int rc;
  26. long t;
  27. for(t=0; t<NUM_THREADS; t++)
  28. {
  29. printf("Main: creating thread %ld\n", t);
  30. // 3/4: use thread attribute
  31. rc = pthread_create(&thread[t], &attr, BusyWork, (void *)t);
  32. if (rc) {
  33. printf("ERROR; return code from pthread_create() is %d\n", rc);
  34. exit(-1);
  35. }
  36. }
  37. // 4/4: release thread attribute
  38. pthread_attr_destroy(&attr);
  39. void *status;
  40. for(t=0; t<NUM_THREADS; t++)
  41. {
  42. rc = pthread_join(thread[t], &status);
  43. if (rc) {
  44. printf("ERROR; return code from pthread_join() is %d\n", rc);
  45. exit(-1);
  46. }
  47. printf("Main: completed join with thread %ld having a status of %ld\n",t,(long)status);
  48. }
  49. printf("Main: program completed. Exiting.\n");
  50. return 0;
  51. }
Copyright © Linux教程網 All Rights Reserved