1、thread类
启动一个线程
#include <thread>
int main() {
void do_some_work();
std::thread my_thread(do_some_work);
}
2、使用资源获取即初始化(RAII)确保函数调用join
在主线程中调用,如果需要等待线程完成,使用std::thread::join()函数,为确保在函数出现状况时候也调用,可以使用try catch;
简单的做法就是声明一个类,并在类的析构函数中使用join
class thread_guard
{
std::thread& t;
public:
explicit thread_guard(std::thread& _t) :t(_t) { }
~thread_guard()
{
if (t.joinable())
{
t.join();
}
}
thread_guard(thread_guard const&) = delete;
thread_guard& operator=(thread_guard const&) = delete;
};
3、在后台运行线程
std::thread t (do_some_background_work) ;
t.detach() ;
assert (!t.joinable()) ;
使用std::thread::detach()函数分离线程。参照UNIX守护线程,被分离的线程通常别称为守护线程。
参考:
C++ Councurrency in Action