linux創建線程之pthread_create


轉自:https://www.cnblogs.com/amanlikethis/p/5537175.html

 

 

函數簡介

  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函數

函數簡介

  函數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時候,傳入的參數被正確打印。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM