本文可任意轉載,但必須注明作者和出處。
【原創】手把手教你Linux下的多線程設計(一)
--Linux下多線程程式設計詳解
原創作者:Frozen_socker(冰棍)
E_mail:
[email protected]線程也被稱為輕權程序(lightweight process)。
在傳統的UNIX上,一個程序讓另一個實體做某個事務是用fork派生子程序的方法處理的。派生子程序的代價比線程要昂貴得多,尤其是在父子程序之間、子程序之間傳遞資訊需要用IPC或其他方法通信。相對比,使用線程有許多優點,如建立線程要比建立程序快的多、一個程序中的線程共享相同的全局存儲區等等。
Linux系統下的多線程遵循POSIX線程接口,稱為pthread,在Linux中,多線程需要使用的頭檔案為<pthread.h>,連接配接時需要使用庫為libpthread.a。
我們編寫一個非常簡單的例子:

//example_1.c

#include <stdio.h>

#include <pthread.h>


void * pthread_func_test(void * arg);


int main()
...{
pthread_t pt1,pt2;
pthread_create(&pt1,NULL,pthread_func_test,"This is the Thread_ONE");
pthread_create(&pt2,NULL,pthread_func_test,"This is the Thread_TWO");
sleep(1); //不加上這句,看不到結果。
}

void * pthread_func_test(void * arg)
printf("%s /n ",arg);
編譯源檔案:

gcc example_1.c -o example -lpthread
編譯環境:
平 台:FC6
版 本:2.6.18-1.2798.fc6
編譯器:gcc 4.1.1 20070105 (Red Hat 4.1.1-51)
運作可執行檔案:
./example
在終端上的輸出結果:

This is the Thread_ONE

This is the Thread_TWO
在example_1這個例子中,一共産生了三個線程,第一個就是main所代表的主線程,另外兩個就是pt1和pt2分别代表的兩個分支線程,這兩個線程由pthread_create函數建立,執行的内容就是寫在函數pthread_func_test裡的東東。
上例涉及到的函數是:pthread_create()
函數原型如下:

int pthread_create(pthread_t *restrict thread,

const pthread_attr_t *restrict attr,

void *(*start_routine)(void*), void *restrict arg);
參數點解:
1、每個線程都有自己的ID即thread ID,可以簡稱tid,呵呵,是不是想起什麼來了?。。。對,和pid有點象。其類型為pthread_t,pthread_t在頭檔案/usr/include/bits/pthreadtypes.h中定義:
typedef unsigned long int pthread_t;
可以看成是線程的标志符。當成功建立一個新線程的時候,系統會為該線程配置設定一個tid,并将該值通過指針傳回給調用它的程式。
2、attr申明線程的屬性。
屬性結構為pthread_attr_t,它在頭檔案/usr/include/pthread.h中定義。設為NULL,表示在這裡我們隻使用線程的預設屬性就可以了。
3、start_routine表示新建立的線程所要執行的例程。線程以調用該函數開始,直到由該函數傳回(return)終止這個線程,或者在start_routine所指向的函數中調用pthread_exit函數終止。start_routine隻有一個參數,該參數由随後的arg指針來指出。
4、arg:也是一個指針,也就是start_routine指針所指向的函數的參數。
傳回值:
當pthread_create調用成功時,該調用傳回0;否則,傳回一個錯誤代碼指出錯誤的類型。
歡迎您發郵件與我交流,但因為工作和時間的關系,我有權對您提出的一些問題不予回答,敬請見諒。