1包含thread头文件及使用boost命名空间
#include<boost/thread.hpp>
2.使用等待当前线程的成员函数
join()一直阻塞等待,直到当前线程结束。
time_join()等待当前线程结束或者最多等待多少时间后返回[当当前线程已经结束但等待时间还未到时也返回]。
3.几种使用方法
第一种方式:最简单方法
- void print_string( const string &str );
-
- int _tmain(int argc, _TCHAR* argv[])
- {
- boost::thread test1( print_string, "hello" );
- test1.join();
- return 0;
- }
第二种方式:在类内部创建线程
(1)类内部静态方法启动线程
class HelloWorld
{
public:
static void hello()
{
std::cout << "Hello world, I''m a thread!"<< std::endl;
}
static void start()
{
boost::thread thrd( hello );
thrd.join();
}
};
int main(int argc, char* argv[])
{
HelloWorld::start();
return 0;
}
在这里start()和hello()方法都必须是static方法。
(2)类内部非静态方法启动线程 将hello成员函数,改为非静态函数。
class HelloWorld
{
public:
void hello()
{
std::cout << "Hello world, I''m a thread!"<< std::endl;
}
void start()
{
boost::thread thrd(boost::bind((&HelloWorld::hello,this));
thrd.join();
}
};
int main(int argc, char* argv[])
{
HelloWorld hl;
hl.start();
return 0;
}
第三种:用类内部函数在类外部创建线程 class HelloWorld
{
public:
void hello(const std::string& str)
{
std::cout << str << std::endl;
}
};
int main(int argc, char* argv[])
{
HelloWorld hl;
boost::thread thr_test(boost::bind((&HelloWorld::hello,hl,"test----"));
thr_test.detach();
return 0;
}