Linux 多線程(轉載)

轉自:http://blog.csdn.net/lanyan822/article/details/7586845

---------------------------------------------------------------------------------------------------


一、什麼是線程?

      線程是進程的一個實體,是CPU調度和分派的基本單位,它是比進程更小的能獨立運行的基本單位。線程自己基本上不擁有系統資源,只擁有一點在運行中必不可少的資源(如程序計數器,一組寄存器和棧),但是它可與同屬一個進程的其他的線程共享進程所擁有的全部資源。

二、什麼時候使用多線程?

     當多個任務可以並行執行時,可以爲每個任務啓動一個線程。

三、線程的創建

     使用pthread_create函數。
    
  1. #include<pthread.h>  
  2. int pthread_create (pthread_t *__restrict __newthread,//新創建的線程ID  
  3.                __const pthread_attr_t *__restrict __attr,//線程屬性  
  4.                void *(*__start_routine) (void *),//新創建的線程從start_routine開始執行  
  5.                void *__restrict __arg)//執行函數的參數  
返回值:成功-0,失敗-返回錯誤編號,可以用strerror(errno)函數得到錯誤信息

四、線程的終止

   三種方式
  • 線程從執行函數返回,返回值是線程的退出碼
  • 線程被同一進程的其他線程取消
  • 調用pthread_exit()函數退出。這裏不是調用exit,因爲線程調用exit函數,會導致線程所在的進程退出。

一個小例子:

啓動兩個線程,一個線程對全局變量num執行加1操作,執行五百次,一個線程對全局變量執行減1操作,同樣執行五百次。

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <pthread.h>  
  4. #include <unistd.h>  
  5. #include <string.h>  
  6.   
  7. int num=0;  
  8. void *add(void *arg) {//線程執行函數,執行500次加法  
  9.     int i = 0,tmp;  
  10.     for (; i <500; i++)  
  11.     {  
  12.         tmp=num+1;  
  13.         num=tmp;  
  14.         printf("add+1,result is:%d\n",num);  
  15.     }  
  16.     return ((void *)0);  
  17. }  
  18. void *sub(void *arg)//線程執行函數,執行500次減法  
  19. {  
  20.     int i=0,tmp;  
  21.     for(;i<500;i++)  
  22.     {  
  23.         tmp=num-1;  
  24.         num=tmp;  
  25.         printf("sub-1,result is:%d\n",num);  
  26.     }  
  27.     return ((void *)0);  
  28. }  
  29. int main(int argc, char** argv) {  
  30.       
  31.     pthread_t tid1,tid2;  
  32.     int err;  
  33.     void *tret;  
  34.     err=pthread_create(&tid1,NULL,add,NULL);//創建線程  
  35.     if(err!=0)  
  36.     {  
  37.         printf("pthread_create error:%s\n",strerror(err));  
  38.         exit(-1);  
  39.     }  
  40.     err=pthread_create(&tid2,NULL,sub,NULL);  
  41.     if(err!=0)  
  42.     {  
  43.         printf("pthread_create error:%s\n",strerror(err));  
  44.          exit(-1);  
  45.     }  
  46.     err=pthread_join(tid1,&tret);//阻塞等待線程id爲tid1的線程,直到該線程退出  
  47.     if(err!=0)  
  48.     {  
  49.         printf("can not join with thread1:%s\n",strerror(err));  
  50.         exit(-1);  
  51.     }  
  52.     printf("thread 1 exit code %d\n",(int)tret);  
  53.     err=pthread_join(tid2,&tret);  
  54.     if(err!=0)  
  55.     {  
  56.         printf("can not join with thread1:%s\n",strerror(err));  
  57.         exit(-1);  
  58.     }  
  59.     printf("thread 2 exit code %d\n",(int)tret);  
  60.     return 0;  
  61. }  
使用g++編譯該文件(g++ main.cpp -o main)。此時會報錯undefined reference to `pthread_create'。


報這個錯誤的原因是:pthread庫不是linux默認的庫,所以在編譯時候需要指明libpthread.a庫。

解決方法:在編譯時,加上-lpthread參數。

執行結果:


乍一看,結果是對的,加500次,減500次,最後結果爲0。但是仔細看所有的輸出,你會發現有異樣的東西。


    導致這個不和諧出現的原因是,兩個線程可以對同一變量進行修改。假如線程1執行tmp=50+1後,被系統中斷,此時線程2對num=50執行了減一操作,當線程1恢復,在執行num=tmp=51。而正確結果應爲50。所以當多個線程對共享區域進行修改時,應該採用同步的方式。

五、線程同步

線程同步的三種方式:

1、互斥量

   互斥量用pthread_mutex_t數據類型來表示。
    兩種方式初始化,第一種:賦值爲常量PTHREAD_MUTEX_INITIALIZER;第二種,當互斥量爲動態分配是,使用pthread_mutex_init函數進行初始化,使用pthread_mutex_destroy函數銷燬。
  
  1. #include<pthread.h>  
  2. int pthread_mutex_init (pthread_mutex_t *__mutex,  
  3.                    __const pthread_mutexattr_t *__mutexattr);  
  4. int pthread_mutex_destroy (pthread_mutex_t *__mutex);  
返回值:成功-0,失敗-錯誤編號
 加解鎖
加鎖調用pthread_mutex_lock,解鎖調用pthread_mutex_unlock。
  1. #include<pthread.h>  
  2. int pthread_mutex_lock (pthread_mutex_t *__mutex);  
  3. int pthread_mutex_unlock (pthread_mutex_t *__mutex);  

使用互斥量修改上一個程序(修改部分用紅色標出):
pthread_mutex_t mylock=PTHREAD_MUTEX_INITIALIZER;
void *add(void *arg) {
    int i = 0,tmp;
    for (; i <500; i++)
    {
        pthread_mutex_lock(&mylock);
        tmp=num+1;
        num=tmp;
        printf("+1,result is:%d\n",num);
        pthread_mutex_unlock(&mylock);
    }
    return ((void *)0);
}
void *sub(void *arg)
{
    int i=0,tmp;
    for(;i<500;i++)
    {
        pthread_mutex_lock(&mylock);
        tmp=num-1;
        num=tmp;
        printf("-1,result is:%d\n",num);
        pthread_mutex_unlock(&mylock);
    }
    return ((void *)0);
}

2、讀寫鎖

   允許多個線程同時讀,只能有一個線程同時寫。適用於讀的次數遠大於寫的情況。
  讀寫鎖初始化:
  
  1. #include<pthread.h>  
  2. int pthread_rwlock_init (pthread_rwlock_t *__restrict __rwlock,  
  3.                 __const pthread_rwlockattr_t *__restrict  
  4.                 __attr);  
  5. int pthread_rwlock_destroy (pthread_rwlock_t *__rwlock);  
返回值:成功--0,失敗-錯誤編號

 加鎖,這裏分爲讀加鎖和寫加鎖。

讀加鎖:
  
  1. int pthread_rwlock_rdlock (pthread_rwlock_t *__rwlock)  

寫加鎖
 
  1. int pthread_rwlock_wrlock (pthread_rwlock_t *__rwlock)  

解鎖用同一個函數
  1. int pthread_rwlock_unlock (pthread_rwlock_t *__rwlock)  

3、條件變量

條件變量用pthread_cond_t數據類型表示。
條件變量本身由互斥量保護,所以在改變條件狀態前必須鎖住互斥量。

條件變量初始化:

第一種,賦值常量PTHREAD_COND_INITIALIZER;第二種,使用pthread_cond_init函數
  1. int pthread_cond_init (pthread_cond_t *__restrict __cond,  
  2.                   __const pthread_condattr_t *__restrict  
  3.                   __cond_attr);  
  4. int pthread_cond_destroy (pthread_cond_t *__cond);  

條件等待

使用pthread_cond_wait等待條件爲真。
  1. pthread_cond_wait (pthread_cond_t *__restrict __cond,  
  2.               pthread_mutex_t *__restrict __mutex)  
這裏需要注意的是,調用pthread_cond_wait傳遞的互斥量已鎖定,pthread_cond_wait將調用線程放入等待條件的線程列表,然後釋放互斥量,在pthread_cond_wait返回時,再次鎖定互斥量。

喚醒線程

pthread_cond_signal喚醒等待該條件的某個線程,pthread_cond_broadcast喚醒等待該條件的所有線程。
  1. int pthread_cond_signal (pthread_cond_t *__cond);  
  2.   
  3. int pthread_cond_broadcast (pthread_cond_t *__cond)  

來一個例子,主線程啓動4個線程,每個線程有一個參數i(i=生成順序),無論線程的啓動順序如何,執行順序只能爲,線程0、線程1、線程2、線程3。
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <pthread.h>  
  4. #include <unistd.h>  
  5. #include <string.h>  
  6. #define DEBUG 1  
  7.   
  8. int num=0;  
  9. pthread_mutex_t mylock=PTHREAD_MUTEX_INITIALIZER;  
  10. pthread_cond_t qready=PTHREAD_COND_INITIALIZER;  
  11. void * thread_func(void *arg)  
  12. {  
  13.     int i=(int)arg;   
  14.     int ret;  
  15.     sleep(5-i);//線程睡眠,然最先生成的線程,最後甦醒  
  16.     pthread_mutex_lock(&mylock);//調用pthread_cond_wait前,必須獲得互斥鎖  
  17.     while(i!=num)  
  18.     {  
  19. #ifdef DEBUG  
  20.         printf("thread %d waiting\n",i);  
  21. #endif  
  22.         ret=pthread_cond_wait(&qready,&mylock);//該函數把線程放入等待條件的線程列表,然後對互斥鎖進行解鎖,這兩部都是原子操作。並且在pthread_cond_wait返回時,互斥量再次鎖住。  
  23.         if(ret==0)  
  24.         {  
  25. #ifdef DEBUG  
  26.             printf("thread %d wait success\n",i);  
  27. #endif  
  28.         }else  
  29.         {  
  30. #ifdef DEBUG  
  31.             printf("thread %d wait failed:%s\n",i,strerror(ret));  
  32. #endif  
  33.         }  
  34.     }  
  35.     printf("thread %d is running \n",i);  
  36.     num++;  
  37.     pthread_mutex_unlock(&mylock);//解鎖  
  38.     pthread_cond_broadcast(&qready);//喚醒等待該條件的所有線程  
  39.     return (void *)0;  
  40. }  
  41. int main(int argc, char** argv) {  
  42.       
  43.     int i=0,err;  
  44.     pthread_t tid[4];  
  45.     void *tret;  
  46.     for(;i<4;i++)  
  47.     {  
  48.         err=pthread_create(&tid[i],NULL,thread_func,(void *)i);  
  49.         if(err!=0)  
  50.         {  
  51.             printf("thread_create error:%s\n",strerror(err));  
  52.             exit(-1);  
  53.         }  
  54.     }  
  55.     for (i = 0; i < 4; i++)  
  56.     {  
  57.         err = pthread_join(tid[i], &tret);  
  58.         if (err != 0)  
  59.         {  
  60.             printf("can not join with thread %d:%s\n", i,strerror(err));  
  61.             exit(-1);  
  62.         }  
  63.     }  
  64.     return 0;  
  65. }  

在非DEBUG模式,執行結果如圖所示:

在DEBUG模式,執行結果如圖所示:

在DEBUG模式可以看出,線程3先被喚醒,然後執行pthread_cond_wait(輸出thread 3 waiting),此時在pthread_cond_wait中先解鎖互斥量,然後進入等待狀態。這是thread 2加鎖互斥量成功,進入pthread_cond_wait(輸出thread 2 waiting) ,同樣解鎖互斥量,然後進入等待狀態。直到線程0,全局變量與線程參數i一致,滿足條件,不進入條件等待,輸出thread 0 is running。全局變量num執行加1操作,解鎖互斥量,然後喚醒所有等待該條件的線程。thread 3 被喚醒,輸出thread 3 wait success。但是不滿足條件,再次執行pthread_cond_wait。如此執行下去,滿足條件的線程執行,不滿足條件的線程等待。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章