linux,pthread(轉)


互斥量、條件變量與pthread_cond_wait()函數的使用,詳解(二)

 

1.Linux“線程”

     進程與線程之間是有區別的,不過linux內核只提供了輕量進程的支持,未實現線程模型。Linux是一種“多進程單線程”的操作系統。Linux本身只有進程的概念,而其所謂的“線程”本質上在內核里仍然是進程。

     大家知道,進程是資源分配的單位,同一進程中的多個線程共享該進程的資源(如作為共享內存的全局變量)。Linux中所謂的“線程”只是在被創建時clone了父進程的資源,因此clone出來的進程表現為“線程”,這一點一定要弄清楚。因此,Linux“線程”這個概念只有在打冒號的情況下才是最准確的。

     目前Linux中最流行的線程機制為LinuxThreads,所采用的就是線程-進程“一對一”模型,調度交給核心,而在用戶級實現一個包括信號處理在內的線程管理機制。LinuxThreads由Xavier Leroy (Xavier.Leroy@inria.fr)負責開發完成,並已綁定在GLIBC中發行,它實現了一種BiCapitalized面向Linux的Posix 1003.1c “pthread”標准接口。Linuxthread可以支持Intel、Alpha、MIPS等平台上的多處理器系統。 

按照POSIX 1003.1c 標准編寫的程序與Linuxthread 庫相鏈接即可支持Linux平台上的多線程,在程序中需包含頭文件pthread. h,在編譯鏈接時使用命令: 

gcc -D -REENTRANT -lpthread xxx. c


其中-REENTRANT宏使得相關庫函數(如stdio.h、errno.h中函數) 是可重入的、線程安全的(thread-safe),-lpthread則意味着鏈接庫目錄下的libpthread.a或libpthread.so文件。使用Linuxthread庫需要2.0以上版本的Linux內核及相應版本的C庫(libc 5.2.18、libc 5.4.12、libc 6)。

     2.“線程”控制 

線程創建 

進程被創建時,系統會為其創建一個主線程,而要在進程中創建新的線程,則可以調用pthread_create: 

pthread_create(pthread_t *thread, const pthread_attr_t *attr, void * 
(start_routine)(void*), void *arg);


start_routine為新線程的入口函數,arg為傳遞給start_routine的參數。 

每個線程都有自己的線程ID,以便在進程內區分。線程ID在pthread_create調用時回返給創建線程的調用者;一個線程也可以在創建后使用pthread_self()調用獲取自己的線程ID: 

pthread_self (void) ;


線程退出 

線程的退出方式有三: 

(1)執行完成后隱式退出; 

(2)由線程本身顯示調用pthread_exit 函數退出; 

pthread_exit (void * retval) ;


(3)被其他線程用pthread_cance函數終止: 

pthread_cance (pthread_t thread) ;


在某線程中調用此函數,可以終止由參數thread 指定的線程。 

如果一個線程要等待另一個線程的終止,可以使用pthread_join函數,該函數的作用是調用pthread_join的線程將被掛起直到線程ID為參數thread的線程終止: 

pthread_join (pthread_t thread, void** threadreturn);

3.線程通信 

線程互斥 

互斥意味着“排它”,即兩個線程不能同時進入被互斥保護的代碼。Linux下可以通過pthread_mutex_t 定義互斥體機制完成多線程的互斥操作,該機制的作用是對某個需要互斥的部分,在進入時先得到互斥體,如果沒有得到互斥體,表明互斥部分被其它線程擁有,此時欲獲取互斥體的線程阻塞,直到擁有該互斥體的線程完成互斥部分的操作為止。 

下面的代碼實現了對共享全局變量x 用互斥體mutex 進行保護的目的: 

int x; // 進程中的全局變量 
pthread_mutex_t mutex; 
pthread_mutex_init(&mutex, NULL); //按缺省的屬性初始化互斥體變量mutex 
pthread_mutex_lock(&mutex); // 給互斥體變量加鎖 
… //對變量x 的操作 
phtread_mutex_unlock(&mutex); // 給互斥體變量解除鎖


線程同步 

同步就是線程等待某個事件的發生。只有當等待的事件發生線程才繼續執行,否則線程掛起並放棄處理器。當多個線程協作時,相互作用的任務必須在一定的條件下同步。 

Linux下的C語言編程有多種線程同步機制,最典型的是條件變量(condition variable)。pthread_cond_init用來創建一個條件變量,其函數原型為: 

pthread_cond_init (pthread_cond_t *cond, const pthread_condattr_t *attr);


pthread_cond_wait和pthread_cond_timedwait用來等待條件變量被設置,值得注意的是這兩個等待調用需要一個已經上鎖的互斥體mutex,這是為了防止在真正進入等待狀態之前別的線程有可能設置該條件變量而產生競爭。pthread_cond_wait的函數原型為: 

pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex);


pthread_cond_broadcast用於設置條件變量,即使得事件發生,這樣等待該事件的線程將不再阻塞: 

pthread_cond_broadcast (pthread_cond_t *cond) ;


pthread_cond_signal則用於解除某一個等待線程的阻塞狀態: 

pthread_cond_signal (pthread_cond_t *cond) ;


pthread_cond_destroy 則用於釋放一個條件變量的資源。 

在頭文件semaphore.h 中定義的信號量則完成了互斥體和條件變量的封裝,按照多線程程序設計中訪問控制機制,控制對資源的同步訪問,提供程序設計人員更方便的調用接口。 

sem_init(sem_t *sem, int pshared, unsigned int val);


這個函數初始化一個信號量sem 的值為val,參數pshared 是共享屬性控制,表明是否在進程間共享。 

sem_wait(sem_t *sem);


調用該函數時,若sem為無狀態,調用線程阻塞,等待信號量sem值增加(post )成為有信號狀態;若sem為有狀態,調用線程順序執行,但信號量的值減一。 

sem_post(sem_t *sem);


調用該函數,信號量sem的值增加,可以從無信號狀態變為有信號狀態。

    

 

4.實例 

下面我們還是以名的生產者/消費者問題為例來闡述Linux線程的控制和通信。一組生產者線程與一組消費者線程通過緩沖區發生聯系。生產者線程將生產的產品送入緩沖區,消費者線程則從中取出產品。緩沖區有N 個,是一個環形的緩沖池。 
[cpp]  view plain  copy
 
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. #define BUFFER_SIZE 16 // 緩沖區數量  
  4. struct prodcons  
  5. {  
  6.     // 緩沖區相關數據結構  
  7.     int buffer[BUFFER_SIZE]; /* 實際數據存放的數組*/  
  8.     pthread_mutex_t lock; /* 互斥體lock 用於對緩沖區的互斥操作 */  
  9.     int readpos, writepos; /* 讀寫指針*/  
  10.     pthread_cond_t notempty; /* 緩沖區非空的條件變量 */  
  11.     pthread_cond_t notfull; /* 緩沖區未滿的條件變量 */  
  12. };  
  13. /* 初始化緩沖區結構 */  
  14. void init(struct prodcons *b)  
  15. {  
  16.     pthread_mutex_init(&b->lock, NULL);  
  17.     pthread_cond_init(&b->notempty, NULL);  
  18.     pthread_cond_init(&b->notfull, NULL);  
  19.     b->readpos = 0;  
  20.     b->writepos = 0;  
  21. }  
  22. /* 將產品放入緩沖區,這里是存入一個整數*/  
  23. void put(struct prodcons *b, int data)  
  24. {  
  25.     pthread_mutex_lock(&b->lock);  
  26.     /* 等待緩沖區未滿*/  
  27.     if ((b->writepos + 1) % BUFFER_SIZE == b->readpos)  
  28.     {  
  29.         pthread_cond_wait(&b->notfull, &b->lock);  
  30.     }  
  31.     /* 寫數據,並移動指針 */  
  32.     b->buffer[b->writepos] = data;  
  33.     b->writepos++;  
  34.     if (b->writepos >= BUFFER_SIZE)  
  35.         b->writepos = 0;  
  36.     /* 設置緩沖區非空的條件變量*/  
  37.     pthread_cond_signal(&b->notempty);  
  38.     pthread_mutex_unlock(&b->lock);  
  39. }   
  40. /* 從緩沖區中取出整數*/  
  41. int get(struct prodcons *b)  
  42. {  
  43.     int data;  
  44.     pthread_mutex_lock(&b->lock);  
  45.     /* 等待緩沖區非空*/  
  46.     if (b->writepos == b->readpos)  
  47.     {  
  48.         pthread_cond_wait(&b->notempty, &b->lock);  
  49.     }  
  50.     /* 讀數據,移動讀指針*/  
  51.     data = b->buffer[b->readpos];  
  52.     b->readpos++;  
  53.     if (b->readpos >= BUFFER_SIZE)  
  54.         b->readpos = 0;  
  55.     /* 設置緩沖區未滿的條件變量*/  
  56.     pthread_cond_signal(&b->notfull);  
  57.     pthread_mutex_unlock(&b->lock);  
  58.     return data;  
  59. }  
  60.   
  61. /* 測試:生產者線程將1 到10000 的整數送入緩沖區,消費者線 
  62.    程從緩沖區中獲取整數,兩者都打印信息*/  
  63. #define OVER ( - 1)  
  64. struct prodcons buffer;  
  65. void *producer(void *data)  
  66. {  
  67.     int n;  
  68.     for (n = 0; n < 10000; n++)  
  69.     {  
  70.         printf("%d --->\n", n);  
  71.         put(&buffer, n);  
  72.     } put(&buffer, OVER);  
  73.     return NULL;  
  74. }  
  75.   
  76. void *consumer(void *data)  
  77. {  
  78.     int d;  
  79.     while (1)  
  80.     {  
  81.         d = get(&buffer);  
  82.         if (d == OVER)  
  83.             break;  
  84.         printf("--->%d \n", d);  
  85.     }  
  86.     return NULL;  
  87. }  
  88.   
  89. int main(void)  
  90. {  
  91.     pthread_t th_a, th_b;  
  92.     void *retval;  
  93.     init(&buffer);  
  94.     /* 創建生產者和消費者線程*/  
  95.     pthread_create(&th_a, NULL, producer, 0);  
  96.     pthread_create(&th_b, NULL, consumer, 0);  
  97.     /* 等待兩個線程結束*/  
  98.     pthread_join(th_a, &retval);  
  99.     pthread_join(th_b, &retval);  
  100.     return 0;  
  101. }  

5.WIN32、VxWorks、Linux線程類比 

目前為止,筆者已經創作了《基於嵌入式操作系統VxWorks的多任務並發程序設計》(《軟件報》2006年5~12期連載)、《深入淺出Win32多線程程序設計》(天極網技術專題)系列,我們來找出這兩個系列文章與本文的共通點。 

看待技術問題要瞄准其本質,不管是Linux、VxWorks還是WIN32,其涉及到多線程的部分都是那些內容,無非就是線程控制和線程通信,它們的許多函數只是名稱不同,其實質含義是等價的,下面我們來列個三大操作系統共同點詳細表單: 

事項 WIN32 VxWorks Linux
線程創建 CreateThread taskSpawn pthread_create
線程終止 執行完成后退出;線程自身調用ExitThread函數即終止自己;被其他線程調用函數TerminateThread函數 執行完成后退出;由線程本身調用exit退出;被其他線程調用函數taskDelete終止 執行完成后退出;由線程本身調用pthread_exit 退出;被其他線程調用函數pthread_cance終止
獲取線程ID GetCurrentThreadId taskIdSelf pthread_self
創建互斥 CreateMutex semMCreate pthread_mutex_init
獲取互斥 WaitForSingleObject、WaitForMultipleObjects semTake pthread_mutex_lock
釋放互斥 ReleaseMutex semGive phtread_mutex_unlock
創建信號量 CreateSemaphore semBCreate、semCCreate sem_init
等待信號量 WaitForSingleObject semTake sem_wait
釋放信號量 ReleaseSemaphore semGive sem_post

6.小結 

本章講述了Linux下多線程的控制及線程間通信編程方法,給出了一個生產者/消費者的實例,並將Linux的多線程與WIN32、VxWorks多線程進行了類比,總結了一般規律。鑒於多線程編程已成為開發並發應用程序的主流方法,學好本章的意義也便不言自明。

[cpp]  view plain  copy
 
  1. #include <stdio.h>                                                                
  2. #include <stdio.h>  
  3. #include <pthread.h>  
  4. void thread(void)                                                                 
  5. {                                                                                 
  6.     int i;                                                                        
  7.     for(i=0;i<3;i++)                                                              
  8.         printf("This is a pthread.\n");                                           
  9. }  
  10.    
  11. int main(void)                                                                    
  12. {                                                                                 
  13.     pthread_t id;                                                                 
  14.     int i,ret;                                                                    
  15.     ret=pthread_create(&id,NULL,(void *) thread,NULL);                            
  16.     if(ret!=0){                                                                   
  17.         printf ("Create pthread error!\n");                                       
  18.         exit (1);                                                                 
  19.     }                                                                             
  20.     for(i=0;i<3;i++)                                                              
  21.         printf("This is the main process.\n");                                    
  22.     pthread_join(id,NULL);                                                        
  23.     return (0);                                                                   
  24. }  

編譯:

gcc example1.c -lpthread -o example1

[cpp]  view plain  copy
 
  1. #include <pthread.h>  
  2. #include <stdio.h>  
  3. #include <sys/time.h>  
  4. #include <string.h>  
  5. #define MAX 10  
  6.    
  7. pthread_t thread[2];  
  8. pthread_mutex_t mut;  
  9. int number=0, i;  
  10.    
  11. void *thread1()  
  12. {  
  13.     printf ("thread1 : I'm thread 1\n");  
  14.     for (i = 0; i < MAX; i++)  
  15.         {  
  16.             printf("thread1 : number = %d\n",number);  
  17.             pthread_mutex_lock(&mut);  
  18.             number++;  
  19.             pthread_mutex_unlock(&mut);  
  20.             sleep(2);  
  21.         }  
  22.     printf("thread1 :主函數在等我完成任務嗎?\n");  
  23.    
  24.     pthread_exit(NULL);  
  25.    
  26. }  
  27.    
  28. void *thread2()  
  29. {  
  30.     printf("thread2 : I'm thread 2\n");  
  31.     for (i = 0; i < MAX; i++)  
  32.         {  
  33.             printf("thread2 : number = %d\n",number);  
  34.             pthread_mutex_lock(&mut);  
  35.             number++;  
  36.             pthread_mutex_unlock(&mut);  
  37.             sleep(3);  
  38.         }  
  39.     printf("thread2 :主函數在等我完成任務嗎?\n");  
  40.     pthread_exit(NULL);  
  41. }  
  42.    
  43.    
  44. void thread_create(void)  
  45. {  
  46.     int temp;  
  47.     memset(&thread, 0, sizeof(thread)); //comment1  
  48.     //創建線程  
  49.     if((temp = pthread_create(&thread[0], NULL, thread1, NULL)) != 0) //comment2  
  50.         printf("線程1創建失敗!\n");  
  51.     else  
  52.         printf("線程1被創建\n");  
  53.     if((temp = pthread_create(&thread[1], NULL, thread2, NULL)) != 0) //comment3  
  54.         printf("線程2創建失敗");  
  55.     else  
  56.         printf("線程2被創建\n");  
  57. }  
  58.    
  59. void thread_wait(void)  
  60. {  
  61.     //等待線程結束  
  62.     if(thread[0] !=0) { //comment4  
  63.         pthread_join(thread[0],NULL);  
  64.         printf("線程1已經結束\n");  
  65.     }  
  66.     if(thread[1] !=0) { //comment5  
  67.         pthread_join(thread[1],NULL);  
  68.         printf("線程2已經結束\n");  
  69.     }  
  70. }  
  71.    
  72. int main()  
  73. {  
  74.     //用默認屬性初始化互斥鎖  
  75.     pthread_mutex_init(&mut,NULL);  
  76.     printf("我是主函數哦,我正在創建線程,呵呵\n");  
  77.     thread_create();  
  78.     printf("我是主函數哦,我正在等待線程完成任務阿,呵呵\n");  
  79.     thread_wait();  
  80.     return 0;  
  81. }  

編譯 :

       gcc -lpthread -o thread_example lp.c

轉自 http://www.cnblogs.com/BiffoLee/archive/2011/11/18/2254540.html

 

作者:懷想天空 

出處:http://www.cnblogs.com/cyyljw/ 
本博客文章,大多系網絡中收集,轉載請注明出處 
相關標簽:嵌入式開發、嵌入式學習


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM