0

I want to access and modify members of a class with an std::thread.

Here is an example:

class bar {
public:
    int a = 5;
    void change_a() {
        a = 10;
        cout << "thread's a=" << a << endl;
    }
};

int main( int argc, char ** argv )
{
    bar object1;

    std::thread t1(&bar::change_a,bar());
    t1.join();

    cout << "object's a=" << object1.a << endl;
    return 0;
}

The result was:

thread's a=10

object's a=5

So the function in the thread modified the variable and printed it, but it obviously did not change the object1 because when I printed that, it was still the same (5).

My question is, where is the variable now 10 if its not an object and how can I work with it?

Community
  • 1
  • 1
acv17
  • 35
  • 6

2 Answers2

3
std::thread t1(&bar::change_a, bar());
                               ^^^

Here you created a temporary bar object. Then, you call change_a on this bar object, so the a is now 10. Now, when the statement ends, the temporary bar object gets destroyed including the variable a.

object1 has nothing to do with that bar, it's just another bar object, and because you're not calling change_a on object1, the a from object1 is 5.

So to answer your question, you are creating 2 objects of type bar, but you're only calling change_a on one bar.

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
1

As threads follow independent code execution.

To Change this you need to pass the address of the object for which you need modification.

bar object1;
std::thread t1(&bar::change_a, &object1 );

As In C++ , Member functions are called with silent this pointer , which is used for further modification of Objects Contents . Thus here if you pass this correctly you can achieve this.

Know more on this pointer C++

Community
  • 1
  • 1
ATul Singh
  • 490
  • 3
  • 15
  • Thank you very much as well, passing a pointer to the object worked! Just a quick question which is a syntax thing, suppose change_a had an argument: void change_a(int x); and say i wanted to pass it 50, would my line simply look like this? std::thread t1(&bar::change_a, 50, &object1); – acv17 May 15 '16 at 22:42