本文共 1743 字,大约阅读时间需要 5 分钟。
std::thread
?????????????C++???????????std::thread
??????????????????????????std::thread
??????????????
std::thread
???????????????????
???????????????????????????????????????
????????????????????????join
?detach
????????????????????????????????
??????????????ThreadRAII
????????????????????
class ThreadRAII {public: enum class DtorAction { join, detach }; ThreadRAII(std::thread&& t, DtorAction a) : action(a), t(std::move(t)) {} ~ThreadRAII() { if (t.joinable()) { if (action == DtorAction::join) { t.join(); } else { t.detach(); } } } std::thread& get() { return t; }private: DtorAction action; std::thread t;};ThreadRAII::ThreadRAII() = default;ThreadRAII&& operator=(ThreadRAII&& other) = default;
bool doWork(std::functionfilter, int maxVal = 10'000'000) { std::vector goodVals; ThreadRAII t(std::thread{[&filter, maxVal, &goodVals](int i) { for (int i = 0; i <= maxVal; ++i) { if (filter(i)) goodVals.push_back(i); } }), ThreadRAII::DtorAction::join; auto nh = t.get().native_handle(); // ... ?????????? if (conditionsAreSatisfied()) { t.get().join(); performComputation(goodVals); return true; } return false;}
std::thread
????????????DtorAction
??std::thread
????????get
?????????????????????ThreadRAII
??????????std::thread
??????????????????????????????
????std::thread
????????????RAII???ThreadRAII
?????????????????????????????????????????????????????
转载地址:http://grru.baihongyu.com/