Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access my class instance from a boost thread?

I have the following code (this is some semi-sudo code, which may not compile):

class FooBar {
public:
    void a();
    void b();
    boost::shared_ptr<boost::thread> m_thread;
    std::string m_test;
};

void FooBar::a() {
    m_test = "Foo bar"
    m_thread = shared_ptr<thread>(new thread(bind(&FooBar::b, this)));
}

void FooBar::b() {
    cout << m_test;
}

The code cout << test does not yield any output, because m_test is "" instead of "Foo bar". Why is this? I thought that passing this as the 2nd argument to bind would allow me to access the same instance from b() - am I incorrect?

like image 306
Nick Bolton Avatar asked Jan 29 '26 03:01

Nick Bolton


1 Answers

Yes, that works. Here's the "real" version, which does in fact print "Foo bar":

#include <boost/make_shared.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>

using namespace boost;

struct FooBar {
    void a();
    void b();
    shared_ptr<thread> m_thread;
    std::string m_test;
};

void FooBar::a() {
    m_test = "Foo bar";
    m_thread = make_shared<thread>(bind(&FooBar::b, this));
}

void FooBar::b() {
    std::cout << m_test;
}

int main() {
    FooBar fb;
    fb.a();
    fb.m_thread->join();
    return 0;
}

The code cout << test does not yield any output, because m_test is ""

I suspect this is because the object was being destroyed before the thread got around to evaluating the member variable. Note the join(), it's very important.

like image 152
Tim Sylvester Avatar answered Jan 31 '26 20:01

Tim Sylvester