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;
}