C++ Concurrency In Action 一些重点

全部来自于gitbook  C++并发编程(中文版)

需要对一个还未销毁的std::thread对象使用join()或detach()。如果想要分离一个线程,可以在线程启动后,直接使用detach()进行分离。如果打算等待对应线程,则需要细心挑选调用join()的位置。当在线程运行之后产生异常,在join()调用之前抛出,就意味着这次调用会被跳过。 避免应用被抛出的异常所终止,就需要作出一个决定。

采用RAII方式来实现线程正常退出

class thread_guard
{
  std::thread& t;
public:
  explicit thread_guard(std::thread& t_):
    t(t_)
  {}
  ~thread_guard()
  {
    if(t.joinable()) // 1
    {
      t.join();      // 2
    }
  }
  thread_guard(thread_guard const&)=delete;   // 3
  thread_guard& operator=(thread_guard const&)=delete;
};

猜你喜欢

转载自www.cnblogs.com/gardenofhu/p/9399601.html