C++ 11 thread

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值