Linux多線程編程(不限Linux)

來源:互聯網
上載者:User

 

——本文一個例子展開,介紹Linux下麵線程的操作、多線程的同步和互斥。

前言

線程?為什麼有了進程還需要線程呢,他們有什麼區別?使用線程有什麼優勢呢?還有多線程編程的一些細節問題,如線程之間怎樣同步、互斥,這些東西將在本文中介紹。我在某QQ群裡見到這樣一道面試題:

是否熟悉POSIX多線程編程技術?如熟悉,編寫程式完成如下功能:

1)有一int型全域變數g_Flag初始值為0;

2) 在主線稱中起動線程1,列印“this is thread1”,並將g_Flag設定為1

3) 在主線稱中啟動線程2,列印“this is thread2”,並將g_Flag設定為2

4) 線程式1需要線上程2退出後才能退出

5) 主線程在檢測到g_Flag從1變為2,或者從2變為1的時候退出

我們帶著這題開始這篇文章,結束之後,大家就都會做了。本文的架構如下:

  • 1、進程與線程
  • 2、使用線程的理由
  • 3、有關線程操作的函數
  • 4、線程之間的互斥
  • 5、線程之間的同步
  • 6、試題最終代碼
1、進程與線程

進程是程式執行時的一個執行個體,即它是程式已經執行到何種程度的資料結構的彙集。從核心的觀點看,進程的目的就是擔當分配系統資源(CPU時間、記憶體等)的基本單位。

線程是進程的一個執行流,是CPU調度和指派的基本單位,它是比進程更小的能獨立啟動並執行基本單位。一個進程由幾個線程組成(擁有很多相對獨立的執行流的使用者程式共用應用程式的大部分資料結構),線程與同屬一個進程的其他的線程共用進程所擁有的全部資源。

"進程——資源分派的最小單位,線程——程式執行的最小單位"

進程有獨立的地址空間,一個進程崩潰後,在保護模式下不會對其它進程產生影響,而線程只是一個進程中的不同執行路徑。線程有自己的堆棧和局部變數,但線程沒有單獨的地址空間,一個線程死掉就等於整個進程死掉,所以多進程的程式要比多線程的程式健壯,但在進程切換時,耗費資源較大,效率要差一些。但對於一些要求同時進行並且又要共用某些變數的並行作業,只能用線程,不能用進程。

2、使用線程的理由

從上面我們知道了進程與線程的區別,其實這些區別也就是我們使用線程的理由。總的來說就是:進程有獨立的地址空間,線程沒有單獨的地址空間(同一進程內的線程共用進程的地址空間)。(下面的內容摘自Linux下的多線程編程)

使用多線程的理由之一是和進程相比,它是一種非常"節儉"的多任務操作方式。我們知道,在Linux系統下,啟動一個新的進程必須分配給它獨立的地址空間,建立眾多的資料表來維護它的程式碼片段、堆棧段和資料區段,這是一種"昂貴"的多任務工作方式。而運行於一個進程中的多個線程,它們彼此之間使用相同的地址空間,共用大部分資料,啟動一個線程所花費的空間遠遠小於啟動一個進程所花費的空間,而且,線程間彼此切換所需的時間也遠遠小於進程間切換所需要的時間。據統計,總的說來,一個進程的開銷大約是一個線程開銷的30倍左右,當然,在具體的系統上,這個資料可能會有較大的區別。

使用多線程的理由之二是線程間方便的通訊機制。對不同進程來說,它們具有獨立的資料空間,要進行資料的傳遞只能通過通訊的方式進行,這種方式不僅費時,而且很不方便。線程則不然,由於同一進程下的線程之間共用資料空間,所以一個線程的資料可以直接為其它線程所用,這不僅快捷,而且方便。當然,資料的共用也帶來其他一些問題,有的變數不能同時被兩個線程所修改,有的子程式中聲明為static的資料更有可能給多線程程式帶來災難性的打擊,這些正是編寫多線程程式時最需要注意的地方。

除了以上所說的優點外,不和進程比較,多線程程式作為一種多任務、並發的工作方式,當然有以下的優點:

  • 提高應用程式響應。這對圖形介面的程式尤其有意義,當一個操作耗時很長時,整個系統都會等待這個操作,此時程式不會響應鍵盤、滑鼠、菜單的操作,而使用多線程技術,將耗時間長度的操作(time consuming)置於一個新的線程,可以避免這種尷尬的情況。
  • 使多CPU系統更加有效。作業系統會保證當線程數不大於CPU數目時,不同的線程運行於不同的CPU上。
  • 改善程式結構。一個既長又複雜的進程可以考慮分為多個線程,成為幾個獨立或半獨立的運行部分,這樣的程式會利於理解和修改。

=============================

從函數調用上來說,進程建立使用fork()操作;線程建立使用clone()操作。Richard Stevens大師這樣說過:

  • fork is expensive. Memory is copied from the parent to the child, all descriptors are duplicated in the child, and so on. Current implementations use a technique called copy-on-write, which avoids a copy of the parent's data space
    to the child until the child needs its own copy. But, regardless of this optimization,
    fork is expensive.

  • IPC is required to pass information between the parent and child after the
    fork. Passing information from the parent to the child before the fork is easy, since the child starts with a copy of the parent's data space and with a copy of all the parent's descriptors. But, returning information from the child to the
    parent takes more work.

Threads help with both problems. Threads are sometimes called lightweight processes since a thread is "lighter weight" than a process. That is, thread creation can be 10–100 times faster than process creation.

All threads within a process share the same global memory. This makes the sharing of information easy between the threads, but along with this simplicity comes the problem of synchronization.

=============================

3、有關線程操作的函數
#include <pthread.h> int pthread_create(pthread_t *tid, const pthread_attr_t *attr, void *(*func) (void *), void *arg);int pthread_join (pthread_t tid, void ** status);pthread_t pthread_self (void);int pthread_detach (pthread_t tid);void pthread_exit (void *status);

pthread_create用於建立一個線程,成功返回0,否則返回Exxx(為正數)。

  • pthread_t *tid:線程id的類型為pthread_t,通常為無符號整型,當調用pthread_create成功時,通過*tid指標返回。
  • const pthread_attr_t *attr:指定建立線程的屬性,如線程優先順序、初始棧大小、是否為守護進程等。可以使用NULL來使用預設值,通常情況下我們都是使用預設值。
  • void *(*func) (void *):函數指標func,指定當新的線程建立之後,將執行的函數。
  • void *arg:線程將執行的函數的參數。如果想傳遞多個參數,請將它們封裝在一個結構體中。

pthread_join用於等待某個線程退出,成功返回0,否則返回Exxx(為正數)。

  • pthread_t tid:指定要等待的線程ID
  • void ** status:如果不為NULL,那麼線程的傳回值儲存在status指向的空間中(這就是為什麼status是二級指標的原因!這種才參數也稱為“值-結果”參數)。

pthread_self用於返回當前線程的ID。

pthread_detach用於是指定線程變為分離狀態,就像進程脫離終端而變為後台進程類似。成功返回0,否則返回Exxx(為正數)。變為分離狀態的線程,如果線程退出,它的所有資源將全部釋放。而如果不是分離狀態,線程必須保留它的線程ID,退出狀態直到其它線程對它調用了pthread_join。

進程也是類似,這也是當我們開啟進程管理器的時候,發現有很多僵死進程的原因!也是為什麼一定要有僵死這個進程狀態。

pthread_exit用於終止線程,可以指定傳回值,以便其他線程通過pthread_join函數擷取該線程的傳回值。

  • void *status:指標線程終止的傳回值。

知道了這些函數之後,我們試圖來完成本文一開始的問題:

1)有一int型全域變數g_Flag初始值為0;

2)在主線稱中起動線程1,列印“this is thread1”,並將g_Flag設定為1

3)在主線稱中啟動線程2,列印“this is thread2”,並將g_Flag設定為2

這3點很簡單嘛!!!不就是調用pthread_create建立線程。代碼如下:

/* * 1)有一int型全域變數g_Flag初始值為0; * * 2)在主線稱中起動線程1,列印“this is thread1”,並將g_Flag設定為1 * * 3)在主線稱中啟動線程2,列印“this is thread2”,並將g_Flag設定為2 * */#include<stdio.h>#include<stdlib.h>#include<pthread.h>#include<errno.h>#include<unistd.h>int g_Flag=0;void* thread1(void*);void* thread2(void*);/* * when program is started, a single thread is created, called the initial thread or main thread. * Additional threads are created by pthread_create. * So we just need to create two thread in main(). */int main(int argc, char** argv){printf("enter main\n");pthread_t tid1, tid2;int rc1=0, rc2=0;rc2 = pthread_create(&tid2, NULL, thread2, NULL);if(rc2 != 0)printf("%s: %d\n",__func__, strerror(rc2));rc1 = pthread_create(&tid1, NULL, thread1, &tid2);if(rc1 != 0)printf("%s: %d\n",__func__, strerror(rc1));printf("leave main\n");exit(0);}/* * thread1() will be execute by thread1, after pthread_create() * it will set g_Flag = 1; */void* thread1(void* arg){printf("enter thread1\n");printf("this is thread1, g_Flag: %d, thread id is %u\n",g_Flag, (unsigned int)pthread_self());g_Flag = 1;printf("this is thread1, g_Flag: %d, thread id is %u\n",g_Flag, (unsigned int)pthread_self());printf("leave thread1\n");pthread_exit(0);}/* * thread2() will be execute by thread2, after pthread_create() * it will set g_Flag = 2; */void* thread2(void* arg){printf("enter thread2\n");printf("this is thread2, g_Flag: %d, thread id is %u\n",g_Flag, (unsigned int)pthread_self());g_Flag = 2;printf("this is thread1, g_Flag: %d, thread id is %u\n",g_Flag, (unsigned int)pthread_self());printf("leave thread2\n");pthread_exit(0);}

這樣就完成了1)、2)、3)這三點要求。編譯執行得如下結果:

netsky@ubuntu:~/workspace/pthead_test$ gcc -lpthread test.c

如果程式中使用到了pthread庫中的函數,除了要#include<pthread.h>,在編譯的時候還有加上-lpthread 選項。

netsky@ubuntu:~/workspace/pthead_test$ ./a.out
enter main
enter thread2
this is thread2, g_Flag: 0, thread id is 3079588720
this is thread1, g_Flag: 2, thread id is 3079588720
leave thread2
leave main
enter thread1
this is thread1, g_Flag: 2, thread id is 3071196016
this is thread1, g_Flag: 1, thread id is 3071196016
leave thread1
但是運行結果不一定是上面的,還有可能是:

netsky@ubuntu:~/workspace/pthead_test$ ./a.out
enter main
leave main
enter thread1
this is thread1, g_Flag: 0, thread id is 3069176688
this is thread1, g_Flag: 1, thread id is 3069176688
leave thread1

或者是:

netsky@ubuntu:~/workspace/pthead_test$ ./a.out
enter main
leave main
等等。這也很好理解因為,這取決於主線程main函數何時終止,線程thread1、thread2是否能夠來得急執行它們的函數。這也是多線程編程時要注意的問題,因為有可能一個線程會影響到整個進程中的所有其它線程!如果我們在main函數退出前,sleep()一段時間,就可以保證thread1、thread2來得及執行。

Attention:大家肯定已經注意到了,我們線上程函數thread1()、thread2()執行完之前都調用了pthread_exit。如果我是調用exit()又或者是return會怎樣呢?自己動手試試吧!

pthread_exit()用於線程退出,可以指定傳回值,以便其他線程通過pthread_join()函數擷取該線程的傳回值。
return是函數返回,只有線程函數return,線程才會退出。
exit是進程退出,如果線上程函數中調用exit,進程中的所有函數都會退出!

“4) 線程式1需要線上程2退出後才能退出”第4點也很容易解決,直接在thread1的函數退出之前調用pthread_join就OK了。

4、線程之間的互斥

上面的代碼似乎很好的解決了問題的前面4點要求,其實不然!!!因為g_Flag是一個全域變數,線程thread1和thread2可以同時對它進行操作,需要對它進行加鎖保護,thread1和thread2要互斥訪問才行。下面我們就介紹如何加鎖保護——互斥鎖。

互斥鎖:

使用互斥鎖(互斥)可以使線程按順序執行。通常,互斥鎖通過確保一次只有一個線程執行代碼的臨界段來同步多個線程。互斥鎖還可以保護單線程代碼。

互斥鎖的相關操作函數如下:

#include <pthread.h> int pthread_mutex_lock(pthread_mutex_t * mptr); int pthread_mutex_unlock(pthread_mutex_t * mptr); //Both return: 0 if OK, positive Exxx value on error

在對臨界資源進行操作之前需要pthread_mutex_lock先加鎖,操作完之後pthread_mutex_unlock再解鎖。而且在這之前需要聲明一個pthread_mutex_t類型的變數,用作前面兩個函數的參數。具體代碼見第5節。

5、線程之間的同步

第5點——主線程在檢測到g_Flag從1變為2,或者從2變為1的時候退出。就需要用到線程同步技術!線程同步需要條件變數。

條件變數:

使用條件變數可以以原子方式阻塞線程,直到某個特定條件為真為止。條件變數始終與互斥鎖一起使用。對條件的測試是在互斥鎖(互斥)的保護下進行的。

如果條件為假,線程通常會基於條件變數阻塞,並以原子方式釋放等待條件變化的互斥鎖。如果另一個線程更改了條件,該線程可能會向相關的條件變數發出訊號,從而使一個或多個等待的線程執行以下操作:

  • 喚醒
  • 再次擷取互斥鎖
  • 重新評分準則

在以下情況下,條件變數可用於在進程之間同步線程:

  • 線程是在可以寫入的記憶體中分配的
  • 記憶體由協作進程共用

“使用條件變數可以以原子方式阻塞線程,直到某個特定條件為真為止。”即可用到第5點,主線程main函數阻塞於等待g_Flag從1變為2,或者從2變為1。條件變數的相關函數如下:

#include <pthread.h> int pthread_cond_wait(pthread_cond_t *cptr, pthread_mutex_t *mptr); int pthread_cond_signal(pthread_cond_t *cptr); //Both return: 0 if OK, positive Exxx value on error

pthread_cond_wait用於等待某個特定的條件為真,pthread_cond_signal用於通知阻塞的線程某個特定的條件為真了。在調用者兩個函數之前需要聲明一個pthread_cond_t類型的變數,用於這兩個函數的參數。

為什麼條件變數始終與互斥鎖一起使用,對條件的測試是在互斥鎖(互斥)的保護下進行的呢?因為“某個特性條件”通常是在多個線程之間共用的某個變數。互斥鎖允許這個變數可以在不同的線程中設定和檢測。

通常,pthread_cond_wait只是喚醒等待某個條件變數的一個線程。如果需要喚醒所有等待某個條件變數的線程,需要調用:

int pthread_cond_broadcast (pthread_cond_t * cptr);

預設情況下面,阻塞的線程會一直等待,知道某個條件變數為真。如果想設定最大的阻塞時間可以調用:

int pthread_cond_timedwait (pthread_cond_t * cptr, pthread_mutex_t *mptr, const struct timespec *abstime);

如果時間到了,條件變數還沒有為真,仍然返回,傳回值為ETIME。

6、試題最終代碼

通過前面的介紹,我們可以輕鬆的寫出代碼了,如下所示:

/* 是否熟悉POSIX多線程編程技術?如熟悉,編寫程式完成如下功能:  1)有一int型全域變數g_Flag初始值為0;  2)在主線稱中起動線程1,列印“this is thread1”,並將g_Flag設定為1  3)在主線稱中啟動線程2,列印“this is thread2”,並將g_Flag設定為2  4)線程式1需要線上程2退出後才能退出  5)主線程在檢測到g_Flag從1變為2,或者從2變為1的時候退出   */#include<stdio.h>#include<stdlib.h>#include<pthread.h>#include<errno.h>#include<unistd.h>typedef void* (*fun)(void*);int g_Flag=0;static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;void* thread1(void*);void* thread2(void*);/* *  when program is started, a single thread is created, called the initial thread or main thread. *  Additional threads are created by pthread_create. *  So we just need to create two thread in main(). */int main(int argc, char** argv){printf("enter main\n");pthread_t tid1, tid2;int rc1=0, rc2=0;rc2 = pthread_create(&tid2, NULL, thread2, NULL);if(rc2 != 0)printf("%s: %d\n",__func__, strerror(rc2));rc1 = pthread_create(&tid1, NULL, thread1, &tid2);if(rc1 != 0)printf("%s: %d\n",__func__, strerror(rc1));pthread_cond_wait(&cond, &mutex);printf("leave main\n");exit(0);}/* * thread1() will be execute by thread1, after pthread_create() * it will set g_Flag = 1; */void* thread1(void* arg){printf("enter thread1\n");printf("this is thread1, g_Flag: %d, thread id is %u\n",g_Flag, (unsigned int)pthread_self());pthread_mutex_lock(&mutex);if(g_Flag == 2)pthread_cond_signal(&cond);g_Flag = 1;printf("this is thread1, g_Flag: %d, thread id is %u\n",g_Flag, (unsigned int)pthread_self());pthread_mutex_unlock(&mutex);pthread_join(*(pthread_t*)arg, NULL);printf("leave thread1\n");pthread_exit(0);}/* * thread2() will be execute by thread2, after pthread_create() * it will set g_Flag = 2; */void* thread2(void* arg){printf("enter thread2\n");printf("this is thread2, g_Flag: %d, thread id is %u\n",g_Flag, (unsigned int)pthread_self());pthread_mutex_lock(&mutex);if(g_Flag == 1)pthread_cond_signal(&cond);g_Flag = 2;printf("this is thread2, g_Flag: %d, thread id is %u\n",g_Flag, (unsigned int)pthread_self());pthread_mutex_unlock(&mutex);printf("leave thread2\n");pthread_exit(0);}

編譯運行可以得到符合要求的結果!

——這篇日誌就算是獻給我自己生日的禮物!

加油,努力,不要放棄!

作者:吳秦
出處:http://www.cnblogs.com/skynet/
本文基於署名 2.5 中國大陸許可協議發布,歡迎轉載,演繹或用於商業目的,但是必須保留本文的署名吳秦(包含連結).

 
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.