简体   繁体   中英

Access a Variable of an Object from Threads

I need help with my c++ programm. I start to Threads beside the main function:

thread Thread1(&Foo::Loop1, info,std::ref(info));
thread Thread2(&Foo::Loop2, info,std::ref(info));

info is an object from the class Foo which contains bool active

later I change the active to true but the value in Loop1 or Loop2 dont change. They are everytime the same.

my prototype function looks like this:

void Loop1(Foo info);
void Loop2(Foo info);

the called function:

void Foo::Loop1(Foo info){
    while (true){
        if (info.active){
          //Stuff
        }
    }
}

So what should I do to pass the value from the object Foo which change in the main function so the value active in the Loop functions are equal.

Thank you for helping :)

std::ref returns an std::reference_wrapper<T> which is implicitly convertable to T& via its conversion operator. When you pass an std::reference_wrapper<T> to a function which accepts a T by value, the conversion operator is invoked, and the function's local copy of T is constructed via its copy constructor.

#include <functional>

class Object
{
    // ...
};

void Func(Object obj)
{
    // Some code which modifies obj
}

int main()
{
    Object obj;
    Func(std::ref(obj));  // <-- Conversion operator invoked, obj passed by value
}

Change the functions to accept Foo by reference.

If the functions are static members, they should have a reference parameter, Foo& .

void Loop1(Foo& info);
void Loop2(Foo& info);

otherwise the threads get copies of the object you passed.

If they are non-static members you don't need to pass the instance at all:

void Foo::Loop1(){
    while (true){
        if (active){
          //Stuff
        }
    }
}

thread Thread1(&Foo::Loop1, info);
thread Thread2(&Foo::Loop2, info);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM