不要这样做。使用boost::thread
.
有了boost::thread
你可以使用任何签名函子开始线程void()
,所以你可以使用std::mem_fun
and std::bind1st
,就像在
struct MyAwesomeThread
{
void operator()()
{
// Do something with the data
}
// Add constructors, and perhaps a way to get
// a result back
private:
// some data here
};
MyAwesomeThread t(parameters)
boost::thread(std::bind1st(std::mem_fun_ref(&t::operator()), t));
编辑:如果你真的想抽象 POSIX 线程(这并不难),你可以这样做(我把 pthread_attr 的初始化留给你)
class thread
{
virtual void run() = 0; // private method
static void run_thread_(void* ptr)
{
reinterpret_cast<thread*>(ptr)->run();
}
pthread_t thread_;
pthread_attr_t attr_;
public:
void launch()
{
pthread_create(&thread_, &attr_, &::run_thread_, reinterpret_cast<void*>(this));
}
};
但boost::thread
便携、灵活且使用非常简单。