boost thread
boost thread类使用简单,能够方便地管理整个线程的全生命周期,应用广泛。
thread配合ios使用时,能够方便地创建线程池,具体请参考boost::asio::io_service创建线程池简单实例。
创建线程
对于一般的使用,是启动一个线程,运行一个函数,在函数内完成特定的任务。
#include <boost/thread.hpp>
void foo()
{
cout << "foo" << endl;
}
boost::thread_group threads;
threads.create_thread(foo);
threads.join_all(); // 等待线程退出
如果是类的成员函数,可以结合boost::bind使用:
class Foo
{
public:
void foo();
};
Foo foo;
boost::thread_group threads;
threads.create_thread(boost::bind(&foo::foo, &foo));
threads.join_all();
销毁线程
有时线程内执行的可能是个死循环,要想在指定的时刻退出该线程,thread也可以轻松做到。
如下程序,线程永远不会退出,程序会卡在等待线程退出的行,因为它永远也无法等到。
void foo()
{
while(true)
cout << "foo" << endl;
}
boost::thread_group threads;
threads.create_thread(foo);
threads.join_all(); // 等待线程退出
即使加上threads_.interrupt_all()也不行,因为没有在程序中设置退出点。
可以通过如下方法设置恰当的退出点:
void foo()
{
try
{
while(true)
{
cout << "foo" << endl;
boost::this_thread::interruption_point(); // 注册线程退出点,注册进thread类
}
} catch (boost::thread_interrupted&) {
std::cout << "interrupted" << std::endl; // 线程会在这里退出
}
}
boost::thread_group threads;
threads.create_thread(foo);
threads.interrupt_all(); // 退出线程,该行执行后,thread类会让线程在执行到退出点后抛出异常退出
threads.join_all(); // 等待线程退出
ok,这样线程就能正常销毁,并被主线程join。