C++ boost :: thread,如何在类中启动一个线程

260*_*607 6 c++ linux multithreading 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()); ...
Run Code Online (Sandbox Code Playgroud)

以后我可以做点什么,

abc.thread.interrupt();
abc.thread.join();
Run Code Online (Sandbox Code Playgroud)

谢谢.

Igo*_* R. 20

你既不需要绑定也不需要指针.

boost::thread m_thread;
//...
m_thread = boost::thread(&ABC::Start, abc);
Run Code Online (Sandbox Code Playgroud)

  • +1:你说得对。有一个带参数的构造函数,相当于使用 bind。我更喜欢绑定,因为我发现它更具可读性。还支持移动线程,我想我喜欢指针,因为我知道发生了什么(复制与移动),但希望一切都朝着移动方向发展...... (2认同)

Guy*_*ton 5

使用boost.bind:

boost::thread(boost::bind(&ABC::Start, abc));
Run Code Online (Sandbox Code Playgroud)

您可能想要一个指针(或shared_ptr):

boost::thread* m_thread;
m_thread = new boost::thread(boost::bind(&ABC::Start, abc));
Run Code Online (Sandbox Code Playgroud)