程式扎記: [C++ 常見問題] 線程的同步 (synchronized) : join

標籤

2010年10月10日 星期日

[C++ 常見問題] 線程的同步 (synchronized) : join

前言 : 
The threads library provides three synchronization mechanisms: 

• mutexes - Mutual exclusion lock: Block access to variables by other threads. This enforces exclusive access by a thread to a variable or set of variables.
• joins - Make a thread wait till others are complete (terminated).
• condition variables - data type pthread_cond_t

這裡將會對 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 代碼 : 
  1. #include   
  2. #include   
  3. #include   
  4.   
  5.   
  6. /* 
  7. * Thread Synchronization : Joins 
  8. */  
  9. void threadSampleTest3(bool b);  
* thread_sample.cpp 代碼 : 
  1. #include "thread_sample.h"  
  2.   
  3. pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;  
  4. int counter = 0;  
  5. #define NTHREADS 10  
  6.   
  7. void *thread_function(void *);  
  8. void threadSampleTest3(bool b) {  
  9.     if(b) {  
  10.         pthread_t thread_id[NTHREADS];  
  11.         for(int i=0; i
  12.             pthread_create(&thread_id[i], NULL, &thread_function, NULL);  
  13.         }  
  14.         for(int i=0; i
  15.             pthread_join(thread_id[i], NULL);  
  16.         }  
  17.         printf("Final count value=%d\n",counter);  
  18.     }  
  19. }  
  20. void *thread_function(void *dummyPtr){  
  21.    printf("Thread number %ld\n", pthread_self());  
  22.    pthread_mutex_lock( &mutex1 );  
  23.    counter++;  
  24.    pthread_mutex_unlock( &mutex1 );  
  25.    return NULL;  
  26. }  

執行結果 : 
Thread number 3625464
...(中間省略)...
Thread number 3627208
Final count value=10


補充說明 : 
* 函式 pthread_join(3) 用法 
* Linux Tutorial : POSIX thread coding 

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!