1. 创建一个boost线程对象
1.1 boost::thread(ThreadFunction);
其中,ThreadFunction是线程的启动函数。创建完成这个对象后,线程就开始运行了。
1.2 如果启动函数有参数要传递,可以调用另一个线程对象构造器,boost::thread(ThreadFunction, Arg1, Arg2, ...);
也可以用绑定器,boost::thread(boost::bind(ThreadFunction, Arg1, Arg2 ...));
1.3 如果线程函数是一个对象的成员函数,可以用绑定器,boost::thread(boost::bind(&MyClass::ThreadFunction, MyObject));
MyClass是一个声明的类,MyObject是这个类的一个对象。
1.4 线程可以放到一个线程组里,这样可以统一管理。boost::thread_group
2. 线程的interrupt
2.1 从线程外部中断一个线程,可以调用线程对象的interrupt(),如下,其中_thread是一个boost::thread对象的share_ptr指针。声明为
2.2 interrupt检查点
如果在线程外部调用了_thread->interrupt(),线程内部的以下这些检查点可以抛出boost::thread_interrupted异常,通过捕获这个异常,我们可以知道线程被interrupt了。
boost::thread::join()
boost::thread::timed_join()
boost::thread::sleep()
boost::condition_variable::wait()
boost::condition_variable::timed_wait()
boost::condition_variable_any::wait()
boost::condition_variable_any::timed_wait()
boost::this_thread::sleep()
boost::this_thread::interruption_point()
2.3 限制interrupt区域
默认可以在线程的任何区域interrupt,boost::this_thread::disable_interruption di; 在这个对象有效区域不能被interrupt。
{ boost::this_thread::restore_interruption ri(di); ///< 这个可以暂时将interrupt打开 boost::this_thread::interruption_point(); }
另外,可以通过boost::thread::interruption_requested()来判断是否在线程外部有interrupt请求。
2.4 特别的情况
我在windows 2003操作系统下测试时发现,如果线程在非interrupt检查点被中断,程序退出,此时,系统会提示一个运行时错误。
windows xp下没有这个问题。
所以最好是除了我们要检查interruption的地方,其它的地方都要将其disable了。