博客
关于我
Effective Modern C++ Item 37 使std::thread型别对象在所有路径皆不可联结
阅读量:130 次
发布时间:2019-02-26

本文共 1708 字,大约阅读时间需要 5 分钟。

std::thread???????

??????C++???????????std::thread??????????????????????????std::thread??????????????

??????????

std::thread???????????????????

  • ?????????????????????????
  • ?????????????????????????

???????????????????????????????????????

?????????

????????????????????????join?detach????????????????????????????????

RAII?????

??????????????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::function
filter, 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/

    你可能感兴趣的文章
    mysql中cast() 和convert()的用法讲解
    查看>>
    mysql中datetime与timestamp类型有什么区别
    查看>>
    MySQL中DQL语言的执行顺序
    查看>>
    mysql中floor函数的作用是什么?
    查看>>
    MySQL中group by 与 order by 一起使用排序问题
    查看>>
    mysql中having的用法
    查看>>
    MySQL中interactive_timeout和wait_timeout的区别
    查看>>
    mysql中int、bigint、smallint 和 tinyint的区别、char和varchar的区别详细介绍
    查看>>
    mysql中json_extract的使用方法
    查看>>
    mysql中json_extract的使用方法
    查看>>
    mysql中kill掉所有锁表的进程
    查看>>
    mysql中like % %模糊查询
    查看>>
    MySql中mvcc学习记录
    查看>>
    mysql中null和空字符串的区别与问题!
    查看>>