简体   繁体   English

c ++线程成员函数接收值

[英]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; 我希望f.value也能达到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); 或者thread t1(&foo::assign_value, &f);

Currently, the thread uses a copy of f . 目前,该线程使用f的副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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