How can I access an instance of a class from a raise thread?

I have the following code (this is a half-court code that cannot 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 << testgives no output, because there m_testis ""instead "Foo bar". Why is this? I thought passing thisas the second argument to bindwould allow me to access the same instance from b()- am I wrong?

+3
source share
1 answer

Yes it works. Here is the "real" version that actually prints the "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 << testgives no output because there m_testis a ""

, , , -. join(), .

+6

Source: https://habr.com/ru/post/1724409/


All Articles