文章目錄
- thread標準庫
- pthread庫
thread標準庫
- C++ 11 后添加了新的標準線程庫 std::thread 類,
- 需引入頭文件<thread>
- 聲明即創建線程對象,如 thread th1; 調用無參構造,生成一個空的線程對象;
- thread th(callable, args),傳入調用函數及參數;
- callable,可為函數;
- callable,可為可調用對象;
- callable,可為lambda 表達式(無名函數)
- g++編譯時,指定 -std=c++11;
在這里插入代碼片
?
pthread庫
- linux下使用pthread庫創建子線程;
- 需包含頭文件<pthread.h>,且編譯時鏈入libpthread.so動態庫;
- pthread_t 線程id類型;
- pthread_create(&curThID, attr, funcName, void* args) 創建線程并執行,成功返回0,并將線程id存入curThID變量地址; attr線程對象的屬性(可NULL); funcName為返回void* 且參數為void*的函數
- 默認為守護線程,主線程結束時,不管子線程有沒有結束,均都隨主線程一起退出;
- pthread_exit(NULL) ,在主線程中等待子線程執行結束;
- pthread_attr_t 線程對象屬性類型;
- pthread_attr_init(&attr) 線程對象屬性初始化;
- pthread_attr_delete(attr) 線程對象屬性刪除;
- pthread_join(thId, status) 連接線程,順序執行;
- pthread_detach() 分離線程;
?
在這里插入代碼片