开发者

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();
    开发者_JAVA技巧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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜