Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runnable class using boost:thread

EDIT > This tutorial provides a good answer

How can I use boost::thread to make a class runnable?

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
}

I don't know if I should inherit boost::thread, have a boost::thread attribute in my class...

I want to be able to do it like this:

Hello hello = Hello();

hello.run();

hello.stop();
like image 708
valentin Avatar asked Sep 16 '26 10:09

valentin


2 Answers

I think you should just put a thread instance inside your class, and in your run() method you can start the thread (with another member function of course). In stop() you can call thread::join() after setting canRun = false.

like image 55
John Zwinck Avatar answered Sep 18 '26 00:09

John Zwinck


I'd say, why not :) See it Live On Coliru

It's c++03 compatible.

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

Note that I used the predicated version of wait() to await the start condition.

like image 42
sehe Avatar answered Sep 18 '26 00:09

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!