boost thread类创建和销毁线程

boost thread使用

一、创建线程示例

#include<iostream>
#include<boost/thread.hpp>
#include<windows.h>
using namespace std;

class Foo
{
public:
	void foo();
};

void Foo::foo()
{
	Sleep(2000);
	cout << "jaminliu" << endl;

	cout << "work_thread exit!" << endl;
}

int main()
{
	Foo foo;
	// boost::thread建立线程
	boost::thread work_thread_;
	work_thread_ = boost::thread(boost::bind(&Foo::foo, &foo));

	Sleep(10000);

	if (work_thread_.joinable())
		work_thread_.join();

	system("pause");
	return 0;
}

执行结果:

 二、销毁线程

如果线程内执行的可能是一个死循环,想要在执行的时刻退出线程,则需要在程序中设置指定的退出点。

#include<iostream>
#include<boost/thread.hpp>
#include<windows.h>

using namespace std;

class Foo
{
public:
	void foo();
};

void Foo::foo()
{
	try
	{
		while (true)
		{
			Sleep(2000);
			cout << "jaminliu" << endl;

			// 注册线程退出点,注册进thread类
			boost::this_thread::interruption_point();
		}
	}
	catch (boost::thread_interrupted&)
	{
		// 线程退出日志
		cout << "work_thread interrupter" << endl;
	}

	cout << "work_thread exit!" << endl;
}

int main()
{
	Foo foo;
	boost::thread work_thread_;
	work_thread_ = boost::thread(boost::bind(&Foo::foo, &foo));

	// 退出线程,该行执行后,thread类控制线程在执行到退出点后抛出异常 退出
	work_thread_.interrupt();

	if (work_thread_.joinable())
		work_thread_.join();

	system("pause");
	return 0;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值