boost::thread有两个构造函数:
(1)thread():构造一个表示当前执行线程的线程对象;
(2)explicit thread(const boost::function0<void>& threadfunc):
(1)thread():构造一个表示当前执行线程的线程对象;
(2)explicit thread(const boost::function0<void>& threadfunc):
boost::function0<void>可以简单看为:一个无返回(返回void),无参数的函数。这里的函数也可以是类重载operator()构成的函数;该构造函数传入的是函数对象而并非是函数指针,这样一个具有一般函数特性的类也能作为参数传入,在下面有例子。
第一种情况:
#include <boost/thread/thread.hpp>
#include <iostream>
void hello()
{
std::cout <<
"Hello world, I''m a thread!"
<< std::endl;
}
int main(int argc, char* argv[])
{
boost::thread thrd(&hello);
thrd.join();
return 0;
}
第二种情况:类重载operator()构成的函数创建线程
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <iostream>
boost::mutex io_mutex;
struct count
{
count(int id) : id(id) { }
void operator()()
{
for (int i = 0; i < 10; ++i)
{
boost::mutex::scoped_lock
lock(io_mutex);
std::cout << id << ": "
<< i << std::endl;
}
}
int id;
};
int main(int argc, char* argv[])
{
boost::thread thrd1(count(1));
boost::thread thrd2(count(2));
thrd1.join();
thrd2.join();
return 0;
}
第三种情况:在类内部对static函数创建线程
#include <boost/thread/thread.hpp>
#include <iostream>
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方法。
第四种情况:使用boost::bind函数创建线程
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <iostream>
class HelloWorld
{
public:
void hello()
{
std::cout <<
"Hello world, I''m a thread!"
<< std::endl;
}
void start()
{
boost::function0< void> f = boost::bind(&HelloWorld::hello,this);
//或boost::function<void()> f = boost::bind(&HelloWorld::hello,this);
boost::thread thrd( f );
thrd.join();
}
};
int main(int argc, char* argv[])
{
HelloWorld hello;
hello.start();
return 0;
}
第五种情况:在Singleton模式内部创建线程
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <iostream>
class HelloWorld
{
public:
void hello()
{
std::cout <<
"Hello world, I''m a thread!"
<< std::endl;
}
static void start()
{
boost::thread thrd( boost::bind
(&HelloWorld::hello,&HelloWorld::getInstance() ) ) ;
thrd.join();
}
static HelloWorld& getInstance()
{
if ( !instance )
instance = new HelloWorld;
return *instance;
}
private:
HelloWorld(){}
static HelloWorld* instance;
};
HelloWorld* HelloWorld::instance = 0;
int main(int argc, char* argv[])
{
HelloWorld::start();
return 0;
}
第六种情况:在类外用类内部函数创建线程
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <string>
#include <iostream>
class HelloWorld
{
public:
void hello(const std::string& str)
{
std::cout <<str<< std::endl;
}
};
int main(int argc, char* argv[])
{
HelloWorld obj;
boost::thread thrd( boost::bind(&HelloWorld::hello,&obj,"Hello
world, I''m a thread!" ) ) ;
thrd.join();
return 0;
}