標籤: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線程簡介和簡單代碼案例