c 併發程式設計(二) 管理執行緒 thread類

2021-09-11 01:30:07 字數 1382 閱讀 5090

同上節所講,執行緒是通過構造std::thread物件來開始的:

void do_some_work();

std::thread my_thread(do_some_work);

使用可呼叫型別:

#include#includeclass func 

};int main()

如果你不做處理,在主線程結束後,thread物件管理的執行緒也被結束了,通過呼叫thread.detach()使執行緒不被銷毀,或使用join()使主線程等待其他執行緒的結束。

使用raii(資源獲取即初始化)等待執行緒完成:

#include#include#includeclass func 

};class thread_guard

~thread_guard()

}};int main()

使用std::ref()包裝需要引用的引數:

void f(int i, int& j) 

int main()

同其他擁有資源的型別(std:;ifstream和std::unique_ptr)一樣std::thread是可移動的非可複製的

以下改進thread_guard類,使它實際上獲得執行緒的所有權,這就能避免其他物件結合或分離該執行緒:

class scoped_thread

} ~scoped_thread()

scoped_thread(scoped_thread&) = delete;

scoped_thread& operator=(scoped_thread const &) = delete;

};void fun()

int main()

); //這裡使用大括號而不是小括號來避免c++將其視為函式宣告

//scoped_thread t(std::thread( //也可以使用lambda表示式來避免

//));

system("pause");

return 0;

}

//獲取機器真正並行執行緒數指標,資訊不可用則返回0

std::cout << std::thread::hardware_concurrency() << std::endl;

//獲取執行緒標識

//1、當前執行緒的識別符號

std::this_thread::get_id()

//2、通過執行緒物件的成員函式獲得

t.get_id()

併發程式設計 2 執行緒管理

一 啟動執行緒 void do something std thread t do something join detach 二 執行緒傳參 執行緒呼叫傳參 void f int i,std string const s std thread t f,3,hello 注意執行緒初始化不會對舛訛的引...

C 併發實戰 (二)執行緒管理

前一篇沒用markdown編輯器感覺不好看,刪了重新發 本篇主要講述執行緒的管理,主要包括建立和使用執行緒 執行緒出現是為了執行任務,執行緒建立時會給乙個入口函式,當這個函式返回時,該執行緒就會退出,最常見的main 函式就是主線程的入口函式,在main 函式返回時主線程就結束了。如何啟動乙個執行緒...

JVM併發程式設計專題 多執行緒管理(執行緒池)

核心執行緒 執行緒在初始化期間建立出來,這樣使用完了扔給下乙個可以重用 開銷少,但會占用記憶體 臨時執行緒 執行緒用完了就扔掉,每次請求都會新建乙個執行緒 開銷大,但是節約記憶體 執行緒池分類 週期 臨時 定長 執行緒池核心 佇列 wokder裝飾器 物件池思想 池屬性裝飾器 引用 清洗 執行緒池應...