pthread_create的淺析

看下面代碼,你是否能得出正確答案呢?

#include<stdio.h>
#include<string.h>
#include <pthread.h>
  
void* print1(void* data){
    printf("1 ");
}
  
void* print2(void* data){
    printf("2 ");
}
 
void* print3(void* data){
    printf("3 ");
}
 
int main(void){
    pthread_t t,t1,t2;
     
    pthread_create(&t,0,print1,NULL);
    pthread_create(&t1,0,print2,NULL);
    pthread_create(&t2,0,print3,NULL);
     
    pthread_join(t,NULL);
    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    printf("\n");
}

此刻,你將提出pthread_create和pthread_join到底是什麼呢?

接下來,我們就來看一看。

pthread_create函數


函數簡介


pthread_create是UNIX環境創建線程函數


頭文件


#include<pthread.h>


函數聲明

int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict arg);


返回值


若成功則返回0,否則返回出錯編號


參數


第一個參數爲指向線程標識符的指針。


第二個參數用來設置線程屬性。


第三個參數是線程運行函數的起始地址。


最後一個參數是運行函數的參數。


另外


在編譯時注意加上-lpthread參數,以調用靜態鏈接庫。因爲pthread並非Linux系統的默認庫

函數pthread_join用來等待一個線程的結束。

頭文件 : #include <pthread.h>

函數定義: 

int pthread_join(pthread_t thread, void **retval);

描述 :pthread_join()函數,以阻塞的方式等待thread指定的線程結束。當函數返回時,被等待線程的資源被收回。如果線程已經結束,那麼該函數會立即返回。並且thread指定的線程必須是joinable的。

參數 :thread: 線程標識符,即線程ID,標識唯一線程。retval: 用戶定義的指針,用來存儲被等待線程的返回值。

返回值 : 0代表成功。 失敗,返回的則是錯誤號。


好了,我們已經瞭解了上面兩個函數,我們現在來看看這個題。

pthread_join(t,NULL)意思是等待線程t執行結束了再執行下面的代碼。但在這之前,3個線程都已提交,它們可能都已經順序隨機地執行了,也可能沒有,所以結果也是不可預測的。

如果想更進一瞭解它的用法,可以看看http://blog.csdn.net/tommy_wxie/article/details/8545253

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章