简体   繁体   中英

c++ thread member function receive value

I have a class member function, which I use in a thread, and I want to set a value of the class with that thread.

#include <thread>
#include <iostream>

using namespace std;

class foo
{
  public:
    void assign_value();
    int value;
};

void foo::assign_value()
{
  value = 1;
  cout << "value within assign_vale() is " << value << '\n';
}


int main()
{
  foo f;

    thread t1(&foo::assign_value, f);
    t1.join();

    cout << "value in main is " << f.value << '\n';

  return 0;
}

The output is as follows:

value within assign_vale() is 1
value in main is 0

I would love to get the f.value also to 1;

The long story of this is that I program a line-following robot which has to be placed on a line and then waits until a button is pressed. It then measures the value of the light sensor and takes this value as the target value. I want to program this waiting-until-button-is-pressed as a thread that pauses. Later on the same button can be pressed to stop the program which is a detached thread. However, I have the problem to get the value from the first thread correctly for all following parts of the program.

Use

  • thread t1(&foo::assign_value, std::ref(f));
  • or thread t1(&foo::assign_value, &f);

Currently, the thread uses a copy of f .

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