C++并发(C++11)-04 转移线程所有权

转移线程所有权

  感觉这一说法是书中为了保持语义正确才这么翻译,让人摸不着头脑。个人觉得“线程变量在不同的线程对象之间传递”这样更好理解一点。

  其实就是std中的move语义。

转移线程所有权的意义

  thread支持了move这一语义,就意味着可以将线程对象用于函数参数或返回值传递,从而更方便的管理线程。

#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类的析构函数防止忘记线程的join或者detach。

posted @ 2020-01-07 11:11  二杠一  Views(299)  Comments(0Edit  收藏  举报