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作默認。
- #include <pthread.h>
- #include <stdio.h>
- #include <stdlib.h>
- #define NUM_THREADS 4
-
- void *BusyWork(void *t)
- {
- double result=0.0;
- long tid = (long)t;
- printf("Thread %ld starting...\n",tid);
- for (int i=0; i<1000000; i++)
- {
- result = result + sin(i) * tan(i);
- }
- printf("Thread %ld done. Result = %e\n",tid, result);
- pthread_exit((void*) t);
- }
-
- int main (int argc, char *argv[])
- {
- pthread_t thread[NUM_THREADS];
- pthread_attr_t attr;
-
- // 1/4: init
- pthread_attr_init(&attr);
- // 2/4: explicitly specify as joinable or detached
- pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
-
- int rc;
- long t;
- for(t=0; t<NUM_THREADS; t++)
- {
- printf("Main: creating thread %ld\n", t);
- // 3/4: use thread attribute
- rc = pthread_create(&thread[t], &attr, BusyWork, (void *)t);
- if (rc) {
- printf("ERROR; return code from pthread_create() is %d\n", rc);
- exit(-1);
- }
- }
-
- // 4/4: release thread attribute
- pthread_attr_destroy(&attr);
-
- void *status;
- for(t=0; t<NUM_THREADS; t++)
- {
- rc = pthread_join(thread[t], &status);
- if (rc) {
- printf("ERROR; return code from pthread_join() is %d\n", rc);
- exit(-1);
- }
- printf("Main: completed join with thread %ld having a status of %ld\n",t,(long)status);
- }
-
- printf("Main: program completed. Exiting.\n");
- return 0;
- }
Copyright ©
Linux教程網 All Rights Reserved