這篇文章主要講解了linux中pthread_create的使用方法,內(nèi)容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
成都創(chuàng)新互聯(lián)公司網(wǎng)絡公司擁有十多年的成都網(wǎng)站開發(fā)建設經(jīng)驗,近1000家客戶的共同信賴。提供成都網(wǎng)站制作、成都網(wǎng)站設計、外貿(mào)營銷網(wǎng)站建設、網(wǎng)站開發(fā)、網(wǎng)站定制、買鏈接、建網(wǎng)站、網(wǎng)站搭建、成都響應式網(wǎng)站建設公司、網(wǎng)頁設計師打造企業(yè)風格,提供周到的售前咨詢和貼心的售后服務
pthread_create函數(shù)
函數(shù)簡介
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,否則返回出錯編號
參數(shù)
第一個參數(shù)為指向線程標識符的指針。
第二個參數(shù)用來設置線程屬性。
第三個參數(shù)是線程運行函數(shù)的地址。
最后一個參數(shù)是運行函數(shù)的參數(shù)。
注意
在編譯時注意加上-lpthread參數(shù),以調(diào)用靜態(tài)鏈接庫。因為pthread并非Linux系統(tǒng)的默認庫。
pthread_join函數(shù)
函數(shù)簡介
函數(shù)pthread_join用來等待一個線程的結(jié)束。
函數(shù)原型為:
extern int pthread_join __P (pthread_t __th, void **__thread_return);
參數(shù):
第一個參數(shù)為被等待的線程標識符
第二個參數(shù)為一個用戶定義的指針,它可以用來存儲被等待線程的返回值。
注意
這個函數(shù)是一個線程阻塞的函數(shù),調(diào)用它的函數(shù)將一直等待到被等待的線程結(jié)束為止,當函數(shù)返回時,被等待線程的資源被收回。如果執(zhí)行成功,將返回0,如果失敗則返回一個錯誤號。
例子:
#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開始運行 */ 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先運行 */ sleep(1); /* 線程pthread睡眠2s,此時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í)行。也就是說是當我們創(chuàng)建了線程pthread之后,兩個線程都在執(zhí)行,證明創(chuàng)建成功。另外,可以看到創(chuàng)建線程pthread時候,傳入的參數(shù)被正確打印。
看完上述內(nèi)容,是不是對linux中pthread_create的使用方法有進一步的了解,如果還想學習更多內(nèi)容,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
當前名稱:linux中pthread_create的使用方法
路徑分享:http://muchs.cn/article20/ipgico.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供虛擬主機、定制網(wǎng)站、品牌網(wǎng)站設計、網(wǎng)頁設計公司、商城網(wǎng)站、定制開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)