0

I am trying to call a functor in std thread and trying to find the data member value after thread complete. But it is not showing expected output, here I think I am missing something, can anyone figure out what is that. The code sample is as below.

#include <iostream>
#include <thread>
using namespace std;

class A 
{
  int value;        
  public:
  A() { value=0;}
  void operator () (int a, int b)
  {
      value = a+b;
      cout << "func called\n";
  }
  void showValue() { cout << value << "\n"; }
};

int main()
{
    A threadfunc;
    thread t1(threadfunc, 4, 5);
    t1.join();
    //threadfunc(4,5);
    threadfunc.showValue();
    //cout<<"Hello World";
    return 0;
}

The output of above code is

func called

0

expected output

func called

9

  • 3
    Threads are internally making copies of arguments. If you want to work with external object, pass it by reference with the help of `reference_wrapper`: `thread t1(std::ref(threadfunc), 4, 5);`. Live demo: https://godbolt.org/z/4c1jsezP7 – Daniel Langr Mar 31 '22 at 07:15
  • @DanielLangr, Ohk I got now, Actually I have also used thread t1(&threadfunc, 4, 5); but it was generating error. Now clear how can I take reference with help of std::ref , Thanks a lot. – Gautam Jangid Mar 31 '22 at 07:19

0 Answers0