C語言多線程

pthread_create函數

    原型:int  pthread_create((pthread_t  *thread,  pthread_attr_t  *attr,  void  *(*start_routine)(void  *),  void  *arg)

    用法:#include  <pthread.h>

    功能:創建線程(實際上就是確定調用該線程函數的入口點),在線程創建以後,就開始運行相關的線程函數。

    說明:thread:線程標識符;

              attr:線程屬性設置;

              start_routine:線程函數的起始地址;

              arg:傳遞給start_routine的參數;

              返回值:成功,返回0;出錯,返回-1。

    舉例:

  1. /*thread.c*/  
  2. #include <stdio.h>  
  3. #include <pthread.h>  
  4.   
  5. /*線程一*/  
  6. void thread_1(void)  
  7. {  
  8.     int i=0;  
  9.     for(i=0;i<=6;i++)  
  10.     {  
  11.         printf("This is a pthread_1.\n");  
  12.         if(i==2)  
  13.             pthread_exit(0);  
  14.         sleep(1);  
  15.     }  
  16. }  
  17.   
  18. /*線程二*/  
  19. void thread_2(void)  
  20. {  
  21.     int i;  
  22.     for(i=0;i<3;i++)  
  23.         printf("This is a pthread_2.\n");  
  24.     pthread_exit(0);  
  25. }  
  26.   
  27. int main(void)  
  28. {  
  29.     pthread_t id_1,id_2;  
  30.     int i,ret;  
  31. /*創建線程一*/  
  32.     ret=pthread_create(&id_1,NULL,(void  *) thread_1,NULL);  
  33.     if(ret!=0)  
  34.     {  
  35.         printf("Create pthread error!\n");  
  36.     return -1;  
  37.     }  
  38. /*創建線程二*/  
  39.      ret=pthread_create(&id_2,NULL,(void  *) thread_2,NULL);  
  40.     if(ret!=0)  
  41.     {  
  42.         printf("Create pthread error!\n");  
  43.     return -1;  
  44.     }  
  45. /*等待線程結束*/  
  46.     pthread_join(id_1,NULL);  
  47.     pthread_join(id_2,NULL);  
  48.     return 0;  
  49. }  

    以下是程序運行結果:

     備註:pthread庫不是Linux系統默認的庫,連接時需要使用靜態庫libpthread.a,所以線程函數在編譯時,需要連接庫函數,如上圖    gcc pthread_create.c -o pthread_create -lpthread


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