C++并發(fā)(C++11)-04 轉(zhuǎn)移線程所有權(quán)
轉(zhuǎn)移線程所有權(quán)
感覺這一說法是書中為了保持語義正確才這么翻譯,讓人摸不著頭腦。個(gè)人覺得“線程變量在不同的線程對象之間傳遞”這樣更好理解一點(diǎn)。
其實(shí)就是std中的move語義。
轉(zhuǎn)移線程所有權(quán)的意義
thread支持了move這一語義,就意味著可以將線程對象用于函數(shù)參數(shù)或返回值傳遞,從而更方便的管理線程。
#include <exception> #include <thread> class scoped_thread { std::thread _t; public: explicit scoped_thread(std::thread t) : _t(std::move(t)) { if (_t.joinable()) { throw std::logic_error(""); } } scoped_thread(const scoped_thread&) = delete; scoped_thread& operator=(const scoped_thread&) = delete; ~scoped_thread() { _t.join(); } }; void foo() {} int main() { scoped_thread t(std::thread(foo)); return 0; }
上面的代碼就利用scoped_thread類的析構(gòu)函數(shù)防止忘記線程的join或者detach。

浙公網(wǎng)安備 33010602011771號