Linux多線程函數解析
Linux多線程函數用得比較多的是下面的3個
pthread_create(),pthread_exit(),pthread_join();它們都是在標頭檔之中。編譯時間需要加靜態庫-lpthread
下面是函數的說明:
pthread_create是UNIX環境建立線程函數
int pthread_create(
pthread_t *restrict tidp,
const pthread_attr_t *restrict_attr,
void*(*start_rtn)(void*),
void *restrict arg);
傳回值
若成功則返回0,否則返回出錯編號
返回成功時,由tidp指向的記憶體單元被設定為新建立線程的線程ID。attr參數用於制定各種不同的線程屬性。新建立的線程從start_rtn函數的地址開始運行,該函數只有一個萬能指標參數arg,如果需要向start_rtn函數傳遞的參數不止一個,那麼需要把這些參數放到一個結構中,然後把這個結構的地址作為arg的參數傳入。
linux下用C開發多線程程式,Linux系統下的多線程遵循POSIX線程介面,稱為pthread。
由 restrict 修飾的指標是最初唯一對指標所指向的對象進行存取的方法,僅當第二個指標基於第一個時,才能對對象進行存取。對對象的存取都限定於基於由 restrict 修飾的指標運算式中。 由 restrict 修飾的指標主要用於函數形參,或指向由 malloc() 分配的記憶體空間。restrict 資料類型不改變程式的語義。 編譯器能通過作出 restrict 修飾的指標是存取對象的唯一方法的假設,更好地最佳化某些類型的常式。
參數
第一個參數為指向線程標識符的指標。
第二個參數用來設定線程屬性。
第三個參數是線程運行函數的起始地址。
最後一個參數是運行函數的參數。
另外,在編譯時間注意加上-lpthread參數,以調用靜態連結庫。因為pthread並非Linux系統的預設庫
pthread_exit(void* retval);
線程通過調用pthread_exit函數終止自身執行,就如同進程在結束時調用exit函數一樣。這個函數的作用是,終止調用它的線程並返回一個指向某個對象的指標。該指標可以通過pthread_join(pthread_t tpid, void **value_ptr)中的第二個參數value_ptr擷取到。
函數pthread_join用來等待一個線程的結束。函數原型為:
extern int pthread_join __P (pthread_t __th, void **__thread_return);
第一個參數為被等待的線程標識符,第二個參數為一個使用者定義的指標,它可以用來儲存被等待線程退出時的傳回值。這個函數是一個線程阻塞的函數,調用它的函數將一直等待到被等待的線程結束為止,當函數返回時,被等待線程的資源被收回。如果執行成功,將返回0,如果失敗則返回一個錯誤號碼。
所有線程都有一個線程號,也就是Thread ID。其類型為pthread_t。通過調用pthread_self()函數可以獲得自身的線程號。
下面是一個簡單的例子,子線程thread_fun會打出5次“this is thread_fun print!”然後調用pthread_exit退出,並返回一個指向字串“this is thread return value!”的指標。在主函數裡面調用pthread_join等待thread_fun線程結束,然後讀取子線程的傳回值到value中,再列印出來。
輸出結果是:
pthread_create ok!
this is thread_fun print!
this is thread_fun print!
this is thread_fun print!
this is thread_fun print!
this is thread_fun print!
pthread exit value: this is thread return value!
#include#include#include#include#include#include//////////////////////////////////////////////////////void *thread_fun(void *arg) { int i=0; char *value_ptr = "this is thread return value!\n"; for (i=0; i<5; i++) { printf("this is thread_fun print!\n"); sleep(1); } pthread_exit((void*)value_ptr);}//////////////////////////////////////////////////////int main(int argc, char **argv) { pthread_t pid; int ret; void* value; ret = pthread_create(&pid, NULL, thread_fun, NULL); if (ret) { printf("pthread_create failed!\nerrno:%d\n", errno); return -1; } printf("pthread_create ok!\n"); pthread_join(pid, &value); printf("pthread exit value: %s\n", value); return 0;}
轉載 http://software.intel.com/zh-cn/blogs/2012/02/14/linux-4/?cid=sw:prccsdn2159