【问题标题】:C++ boost::thread, how to start a thread inside a classC++ boost::thread,如何在类中启动线程
【发布时间】:2012-02-26 23:09:36
【问题描述】:

如何在对象中启动线程?例如,

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();

谢谢。

【问题讨论】:

    标签: c++ linux multithreading boost


    【解决方案1】:

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

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

    【讨论】:

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

    使用 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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-31
      • 1970-01-01
      • 2017-10-24
      • 2012-02-29
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 2023-03-29
      相关资源
      最近更新 更多