2012-02-26 251 views
6

如何在对象内启动线程?例如,C++ boost ::线程,如何启动线程内的线程

class ABC 
{ 
public: 
void Start(); 
double x; 
boost::thread m_thread; 
}; 

ABC abc; 
... do something here ... 
... how can I start the thread with Start() function?, ... 
... e.g., abc.m_thread = boost::thread(&abc.Start()); ... 

这样,以后我可以这样做,

abc.thread.interrupt(); 
abc.thread.join(); 

感谢。

回答

6

使用boost.bind:

boost::thread(boost::bind(&ABC::Start, abc)); 

你可能需要一个指针(或一个shared_ptr):

boost::thread* m_thread; 
m_thread = new boost::thread(boost::bind(&ABC::Start, abc)); 
+0

谢谢盖伊,它工作得很好。 – 2607 2012-02-26 23:50:26

15

你既不需要绑定,也不指针。

boost::thread m_thread; 
//... 
m_thread = boost::thread(&ABC::Start, abc); 
+0

+1:你说得对。有一个参数相当于使用绑定的构造函数。我更喜欢绑定,因为我发现它更具可读性。还有支持移动线程,我想我喜欢指针,因为我知道发生了什么(复制与移动),但希望一切都朝着移动... – 2012-02-27 21:26:59

+0

这应该是接受的答案 – user463035818 2017-06-01 14:08:43