使用 boost:thread 的可运行类

Runnable class using boost:thread

本文关键字:运行 thread boost 使用      更新时间:2023-10-16

编辑> 本教程提供了一个很好的答案

如何使用boost::thread使类可运行?

class Hello
{
    void run();
    bool canRun();
    boost::condition_variable cond;
    boost::mutex mut;
};
Hello::run()
{
    boost::unique_lock<boost::mutex> lock(this->mut);
    while (!this->canRun())
        this->cond.wait(lock);
    // do my stuff
}

我不知道我是否应该继承boost::thread,在我的类中有一个boost::thread属性......

我希望能够这样做:

Hello hello = Hello();
hello.run();
hello.stop();

我认为你应该在你的类中放一个线程实例,在你的 run() 方法中你可以启动线程(当然使用另一个成员函数)。 在 stop() 中,你可以在设置 canRun = false 后调用 thread::join()。

我会

说,为什么不:)在科里鲁现场观看

它与 c++03 兼容。

#include <boost/thread.hpp>
struct Hello
{
    void run();
    bool canRun() { return true; }
    boost::condition_variable cond;
    boost::mutex mut;
};
void Hello::run()
{
    boost::unique_lock<boost::mutex> lock(this->mut);
    cond.wait(lock, boost::bind(&Hello::canRun, this));
    std::cout << "Done";
}
int main()
{
    Hello obj;
    boost::thread th(&Hello::run, &obj);
    boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
    {
        boost::lock_guard<boost::mutex> lk(obj.mut);
        obj.cond.notify_one();
    }
    th.join(); 
}

请注意,我使用了 wait() 的谓词版本来等待启动条件。