2012年12月10日 星期一

在 Linux 中,用 Eclipse 開發 Pthreads 程式

因為開發應用程式的需求,要充份發揮多核心的 CPU 運算能力,就需要將原有程式改寫成「多執行緒(Multi-Threads)」,本想直接使用 OpenMP 這類新的技術,經研讀相關資料、整理後,覺得先改成 POSIX Threads 的程式,應該比較適合些。既然決定了,就把以前的 POSIX threads 筆記先拿出來整理、更新一下,順便複習複習。
    要在 Linux 開發時使用 Eclipse 比較直覺,這次的整理也依一般的慣例,就由在 Eclipse 中寫個 Hello Pthreads 程式開始,另外再加上一些更新後的參考網站連結。
之前寫過幾篇用 Eclipse 開發的文章,所以這次就直接切入重點。想要多瞭解 Eclipse 的安裝、設定的讀者,請自行參考之前的發文。

:開發筆記整理的順序,會因筆者程式的需求而調整,不一定依學習流程撰寫,請讀者包涵。

一、建立新專案 HelloPthreads

先去下載一個現成的 HelloPthreads.c 程式,這是美國 Lawrence Livermore 國家實驗室 "POSIX Threads Programming 教程" 中的範例。參考 “在 Linux 中,用 Eclipse 寫第一個程式 HelloWorld” 中的步驟,建立一新專案。假設將專案名稱定為『HelloPthreads』,則會產生一個名為 HelloPthreads.c 的 C 程式檔,而內容為 HelloWorld 的專案,但是有完整的專案架構。
    接著,將剛才下載的範例貼到 HelloPthreads.c 上,覆蓋掉原來的 HelloWorld 程式。這時還不能編譯,要先完成下一步驟的專案參數設定才行。

二、設定專案參數 -lpthread

先點選左欄「專案瀏覽器」的專案名稱,再從「選單」→「專案」點選「內容)」,以設定專案的內容。
  • 當跳出專案設定視窗後,從左欄的「C/C++ Build」點選「Settings」,接著再設定右欄 Settings。
  • 在右欄中的「Configuration:」選 "[All Configurations]",使「除錯版」與「釋出版」有相同設定。若「除錯版」與「釋出版」的設定要求不同時,就要分開設定。
  • 最後要設定 Link (鏈結) 的參數,從「Tool Settings」→「GCC C Linker」點選「Libraries」,在右方的「Libraries (-l)」中按『✚』加上 "pthread" 。
按確定後,完成專案的連結參數設定。

三、編譯、執行

按「鐵鎚」選定「釋出版」模式,再按一次「鐵鎚」就會進行「編譯」。接著按「執行」鈕,開始執行程式。測試的電腦是『四核八執行緒』的處理器,多按幾次會發現「執行緒」的執行順序、結束的時間都不一樣:
In main: creating thread 0
In main: creating thread 1
In main: creating thread 2
Hello World! It's me, thread #0!
Hello World! It's me, thread #2!
In main: creating thread 3
Hello World! It's me, thread #1!
In main: creating thread 4
Hello World! It's me, thread #3!
Hello World! It's me, thread #4!

In main: creating thread 0
In main: creating thread 1
In main: creating thread 2
Hello World! It's me, thread #1!
In main: creating thread 3
Hello World! It's me, thread #2!
Hello World! It's me, thread #0!
In main: creating thread 4
Hello World! It's me, thread #3!
Hello World! It's me, thread #4!

四、幾個不錯的參考網站

網路上有關 POSIX Threads 的資料很多,僅就一些筆者常參考的網站列出。

已測試版本:

  • Fedora: 14, 17

沒有留言:

張貼留言

感謝你耐心看完本文,歡迎留下任何指正、建議,筆者會儘快回應。(English is also welcome.)