要點:
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之類的很重要,因爲他們作用是把一般函數轉換爲函數對象;