本文可任意轉載,但必須註明作者和出處。
【原創】手把手教你Linux下的多線程設計(一)
--Linux下多線程編程詳解
原創作者:Frozen_socker(冰棍)
E_mail:dlskyfly@163.com
線程也被稱為
輕權進程(
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;否則,返回一個錯誤碼指出錯誤的類型。
歡迎您發郵件與我交流,但因為工作和時間的關係,我有權對您提出的一些問題不予回答,敬請見諒。