說明:本文轉自多線程編程之pthread_create函數應用,在此基礎上筆者作了些許改動。html
pthread_create函數編程
函數簡介多線程
pthread_create是UNIX環境建立線程函數函數
頭文件post
#include<pthread.h>url
函數聲明spa
int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict arg);線程
返回值指針
若成功則返回0,不然返回出錯編號rest
參數
第一個參數爲指向線程標識符的指針。
第二個參數用來設置線程屬性。
第三個參數是線程運行函數的地址。
最後一個參數是運行函數的參數。
注意
在編譯時注意加上-lpthread參數,以調用靜態連接庫。由於pthread並不是Linux系統的默認庫。
pthread_join函數
函數簡介
函數pthread_join用來等待一個線程的結束。
函數原型爲:
extern int pthread_join __P (pthread_t __th, void **__thread_return);
參數:
第一個參數爲被等待的線程標識符
第二個參數爲一個用戶定義的指針,它能夠用來存儲被等待線程的返回值。
注意
這個函數是一個線程阻塞的函數,調用它的函數將一直等待到被等待的線程結束爲止,當函數返回時,被等待線程的資源被收回。若是執行成功,將返回0,若是失敗則返回一個錯誤號。
例子:
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<pthread.h> 4 5 /* 聲明結構體 */ 6 struct member 7 { 8 int num; 9 char *name; 10 }; 11 12 /* 定義線程pthread */ 13 static void * pthread(void *arg) 14 { 15 struct member *temp; 16 17 /* 線程pthread開始運行 */ 18 printf("pthread start!\n"); 19 20 /* 令主線程繼續執行 */ 21 sleep(2); 22 23 /* 打印傳入參數 */ 24 temp = (struct member *)arg; 25 printf("member->num:%d\n",temp->num); 26 printf("member->name:%s\n",temp->name); 27 28 return NULL; 29 } 30 31 /* main函數 */ 32 int main(int agrc,char* argv[]) 33 { 34 pthread_t tidp; 35 struct member *b; 36 37 /* 爲結構體變量b賦值 */ 38 b = (struct member *)malloc(sizeof(struct member)); 39 b->num=1; 40 b->name="mlq"; 41 42 /* 建立線程pthread */ 43 if ((pthread_create(&tidp, NULL, pthread, (void*)b)) == -1) 44 { 45 printf("create error!\n"); 46 return 1; 47 } 48 49 /* 令線程pthread先運行 */ 50 sleep(1); 51 52 /* 線程pthread睡眠2s,此時main能夠先執行 */ 53 printf("mian continue!\n"); 54 55 /* 等待線程pthread釋放 */ 56 if (pthread_join(tidp, NULL)) 57 { 58 printf("thread is not exit...\n"); 59 return -2; 60 } 61 62 return 0; 63 }
編譯與執行結果
編譯與執行結果以下圖所示,能夠看到主線程main和線程pthread交替執行。也就是說是當咱們建立了線程pthread以後,兩個線程都在執行,證實建立成功。另外,能夠看到建立線程pthread時候,傳入的參數被正確打印。