The threads library provides three synchronization mechanisms:
這裡將會對 Join 使用作簡單使用介紹 :
Join 簡介 :
A join is performed when one wants to wait for a thread to finish. A thread calling routine may launch multiple threads then wait for them to finish to get the results. One wait for the completion of the threads with a join. When a joinable thread terminates, its memory resources (thread descriptor and stack) are not deallocated until another thread performs pthread_join on it. Therefore, pthread_join must be called once for each joinable thread created to avoid memory leaks.
範例代碼 :
* thread_sample.h 代碼 :
- #include
- #include
- #include
- /*
- * Thread Synchronization : Joins
- */
- void threadSampleTest3(bool b);
- #include "thread_sample.h"
- pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
- int counter = 0;
- #define NTHREADS 10
- void *thread_function(void *);
- void threadSampleTest3(bool b) {
- if(b) {
- pthread_t thread_id[NTHREADS];
- for(int i=0; i
- pthread_create(&thread_id[i], NULL, &thread_function, NULL);
- }
- for(int i=0; i
- pthread_join(thread_id[i], NULL);
- }
- printf("Final count value=%d\n",counter);
- }
- }
- void *thread_function(void *dummyPtr){
- printf("Thread number %ld\n", pthread_self());
- pthread_mutex_lock( &mutex1 );
- counter++;
- pthread_mutex_unlock( &mutex1 );
- return NULL;
- }
執行結果 :
補充說明 :
* 函式 pthread_join(3) 用法
* Linux Tutorial : POSIX thread coding
沒有留言:
張貼留言