了解線程
特此說明: 劉超的趣談linux操作系統是比較重要的參考資料,本文大部分內容和所有圖片來源于這個專欄。

背景知識
之前了解了進程的創建過程,其實進程默認也有一個主線程(也可以包含其他線程)。線程是負責執行二進制指令的,它會根據項目執行計劃書,一行一行執行下去。進程要比線程管的寬多了,除了執行指令之外,內存、文件系統等等都要它來管。
例如,此時有一個開發網站的項目。我們想把它拆解成多個網頁任務,并行執行,最后做一個整合。類似的,在程序實現上,也可以將一個功能拆分成多個子任務。可以使用多進程的并行方案,但是有兩個問題
第一,創建進程占用資源太多;
第二,進程之間的通信需要數據在不同的內存空間傳來傳去,無法共享。
使用多線程可以很好的解決這兩個問題(多個線程是共享一個進程的資源)。那么,如何創建一個線程任務,線程間又如何對數據操作的呢?
代碼示例
1、 編輯&編譯&運行
# download.c
//download.c #include 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 # 編譯 gcc download.c -lpthread 1 # 運行 # ./a.out creating thread 0, please help me to download file1.avi creating thread 1, please help me to download file2.rmvb I am downloading the file file1.avi! creating thread 2, please help me to download file3.mp4 I am downloading the file file2.rmvb! creating thread 3, please help me to download file4.wmv I am downloading the file file3.mp4! creating thread 4, please help me to download file5.flv I am downloading the file file4.wmv! I am downloading the file file5.flv! I finish downloading the file within 83 minutes! I finish downloading the file within 77 minutes! I finish downloading the file within 86 minutes! I finish downloading the file within 15 minutes! I finish downloading the file within 93 minutes! Thread 0 downloads the file file1.avi in 83 minutes. Thread 1 downloads the file file2.rmvb in 86 minutes. Thread 2 downloads the file file3.mp4 in 77 minutes. Thread 3 downloads the file file4.wmv in 93 minutes. Thread 4 downloads the file file5.flv in 15 minutes. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 2、 總體流程 線程數據 1、 線程數據分類 線程棧上的本地數據,相當于函數中的局部變量。通過ulimit -a命令查看線程棧的空間大小。 在整個進程里共享的全局數據,相當于程序中的全部變量。多個線程同時對共享資源訪問會造成沖突,所以需要額外的機制控制。 線程私有數據,通過key-value形式存儲。通過函數接口操作。多線程可以使用同一個key值,但是各自有不同的value;在線程退出自動析構釋放value。 2、 總結框圖 3、 數據保護 對共享數據的訪問過程中,使用同步互斥機制 互斥鎖(Mutex) 互斥鎖(Mutex) + 條件變量 信號量 參考資料 極客專欄 - 線程:如何讓復雜的項目并行執行? 線程同步和互斥的區別 任務調度
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。