要点:
1 线程对象不可以复制,但是可以转移;
2 当线程对象析构时,线程变为detached,但线程并未结束;也可以通过detach()
方法来显示的detached;
3 等待线程结束,可以用join()
or timed_join()
方法;
4 可以调用interrupt()
方法结束一个线程,线程会在运行到interruption points时抛出boost::thread_interrupted
异常; interruption points如下:
boost::thread::join()
boost::thread::timed_join()
boost::condition_variable::wait()
boost::condition_variable::timed_wait()
boost::condition_variable_any::wait()
boost::condition_variable_any::timed_wait()
boost::thread::sleep()
boost::this_thread::sleep()
boost::this_thread::interruption_point()
所以,从boost文档这一点上可以知道,要正常手法结束一个线程,而非terminated一个线程,只能在线程的执行代码中设立很多检查点,当在某个检查点处检查,发现线程退出标志被设定,则马上返回,不执行其余工作,从而结束线程;
5 如果不能线程的执行被interrupt,可以通过定义一个boost::this_thread::disable_interruption
类型变量实现,从定义到析构中间的代码不会被interrupt的,相反的操作是boost::this_thread::restore_interruption
类型;都是通过RIIA来实现的;
6 线程id可以通过get_id()
得到;
7 Namespace this_thread
有许多常用函数:
-
Non-member function
get_id()
Non-member function interruption_point()
Non-member function interruption_requested()
Non-member function interruption_enabled()
Non-member function sleep()
Non-member function yield()
Class disable_interruption
Class restore_interruption
Non-member function template at_thread_exit()
8 说了半天,给个例子;
#include <boost/thread/thread.hpp>
#include <iostream>
void helloworld()
{
std::cout << "Hello World!" << std::endl;
}
struct helloworld
{
helloworld(const char* who) : m_who(who) { }
void operator()()
{
std::cout << m_who << "says, \"Hello World.\"" << std::endl;
}
const char* m_who;
};
int main()
{
boost::thread thrd1(&helloworld);
thrd.join();
boost::thread thrd2(helloworld("Bob"));
thrd.join();
boost::thread thrd3(boost::bind(&helloworld, "Bob"));
thrd.join();
}
总结,boost中什么都是对象,线程函数也以函数对象的形式被调用;所以说boost中function,bind之类的很重要,因为他们作用是把一般函数转换为函数对象;