linux創(chuàng)建線程之pthread_create的具體使用
pthread_create函數(shù)
函數(shù)簡(jiǎn)介
pthread_create是UNIX環(huán)境創(chuàng)建線程函數(shù)
頭文件
#include<pthread.h>
函數(shù)聲明
int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict arg);
返回值
若成功則返回0,否則返回出錯(cuò)編號(hào)
參數(shù)
第一個(gè)參數(shù)為指向線程標(biāo)識(shí)符的指針。
第二個(gè)參數(shù)用來設(shè)置線程屬性。
第三個(gè)參數(shù)是線程運(yùn)行函數(shù)的地址。
最后一個(gè)參數(shù)是運(yùn)行函數(shù)的參數(shù)。
注意
在編譯時(shí)注意加上-lpthread參數(shù),以調(diào)用靜態(tài)鏈接庫。因?yàn)閜thread并非Linux系統(tǒng)的默認(rèn)庫。
pthread_join函數(shù)
函數(shù)簡(jiǎn)介
函數(shù)pthread_join用來等待一個(gè)線程的結(jié)束。
函數(shù)原型為:
extern int pthread_join __P (pthread_t __th, void **__thread_return);
參數(shù):
第一個(gè)參數(shù)為被等待的線程標(biāo)識(shí)符
第二個(gè)參數(shù)為一個(gè)用戶定義的指針,它可以用來存儲(chǔ)被等待線程的返回值。
注意
這個(gè)函數(shù)是一個(gè)線程阻塞的函數(shù),調(diào)用它的函數(shù)將一直等待到被等待的線程結(jié)束為止,當(dāng)函數(shù)返回時(shí),被等待線程的資源被收回。如果執(zhí)行成功,將返回0,如果失敗則返回一個(gè)錯(cuò)誤號(hào)。
例子:
#include<stdio.h> #include<stdlib.h> #include<pthread.h> /* 聲明結(jié)構(gòu)體 */ struct member { int num; char *name; }; /* 定義線程pthread */ static void * pthread(void *arg) { struct member *temp; /* 線程pthread開始運(yùn)行 */ printf("pthread start!\n"); /* 令主線程繼續(xù)執(zhí)行 */ sleep(2); /* 打印傳入?yún)?shù) */ temp = (struct member *)arg; printf("member->num:%d\n",temp->num); printf("member->name:%s\n",temp->name); return NULL; } /* main函數(shù) */ int main(int agrc,char* argv[]) { pthread_t tidp; struct member *b; /* 為結(jié)構(gòu)體變量b賦值 */ b = (struct member *)malloc(sizeof(struct member)); b->num=1; b->name="mlq"; /* 創(chuàng)建線程pthread */ if ((pthread_create(&tidp, NULL, pthread, (void*)b)) == -1) { printf("create error!\n"); return 1; } /* 令線程pthread先運(yùn)行 */ sleep(1); /* 線程pthread睡眠2s,此時(shí)main可以先執(zhí)行 */ printf("mian continue!\n"); /* 等待線程pthread釋放 */ if (pthread_join(tidp, NULL)) { printf("thread is not exit...\n"); return -2; } return 0; }
編譯與執(zhí)行結(jié)果
編譯與執(zhí)行結(jié)果如下圖所示,可以看到主線程main和線程pthread交替執(zhí)行。也就是說是當(dāng)我們創(chuàng)建了線程pthread之后,兩個(gè)線程都在執(zhí)行,證明創(chuàng)建成功。另外,可以看到創(chuàng)建線程pthread時(shí)候,傳入的參數(shù)被正確打印。
到此這篇關(guān)于linux創(chuàng)建線程之pthread_create的具體使用的文章就介紹到這了,更多相關(guān)linux pthread_create內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。