LINUX線程簡介和簡單代碼案例

來源:互聯網
上載者:User

標籤:read   地址空間   join()   案例   tin   creat   時間   計數器   系統   

0x00.什麼是線程
    是電腦中獨立啟動並執行最小單位,運行時佔用很少的系統資源。可以把線程看成是作業系統分配CPU時間的基本單元。一個進程可以擁有一個至多個線程。它線程在進程內部共用地址空間、開啟的檔案描述符等資源。同時線程也有其私人的資料資訊,包括:線程號、寄存器(程式計數器和堆棧指標)、堆棧、訊號掩碼、優先順序、線程私人儲存空間

 

0x01.為什麼使用線程
    在某個時間片需要同時執行兩件或者兩件以上的事情

0x02.怎麼使用線程

   A. 使用到的函數

    int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);        int pthread_join(pthread_t thread, void **retval);

  B.代碼案例

  測試環境:ubuntu 16.0

  編譯器:       g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609 (查看版本指令:g++ --version)

  編譯註意事項: g++ thread.cpp -o thread -lpthread

 1     #include <stdio.h> 2     #include <stdlib.h> 3     #include <string.h> 4     #include <error.h> 5     #include <pthread.h> 6      7     //要執行的線程方法 8     void* ThreadFunc(void* argc) 9     {10         printf("thread start \n");11     }12     13     int main(int argc,char* argv[])14     {15         pthread_t pid;16         void* ret_val;17         18         //建立子線程並綁定子線程執行方法19         int create_status = pthread_craete(&pthread_t, NULL,20                 ThreadFunc, NULL);21         if(0 != create_status)22         {23             perror("main()->pthread_create");24             exit(1);25         }26         27         //等待建立的子線程先執行28         pthread_join(pid, &ret_val);29         30         return 0;31     }

 

0x03.遇到的坑

      先沒有使用pthread_join(),執行./thread 沒有任何資訊。後來查資料瞭解到 pthread_create() 建立線程成功後,主線程(main())會繼續執行。

      之後調用pthread_join()函數,會等待子線程執行完畢,再繼續主線程。

 

 


  

LINUX線程簡介和簡單代碼案例

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.