1 year ago

#357710

test-img

Gautam Jangid

Using functor in thread in c++

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

c++

multithreading

std

functor

0 Answers

Your Answer

Accepted video resources