6

I want to call a method (for this example std::thread constructor) with lambda function, passing int value:

int a=10;

std::thread _testThread = thread([a](int _a){
  //do stuff using a or _a ?
});
_testThread.detach();

I don't know how to properly write such function, I get this error: C2064: term does not evaluate to a function taking 0 arguments

Dainius Kreivys
  • 525
  • 2
  • 8
  • 19

3 Answers3

14

std::thread takes a callable object as well as any arguments to pass to it. If you give no arguments, std::thread will try to call that object with no arguments, hence the error.

If you need a parameter:

std::thread _testThread{[a](int _a) {
    std::cout << a << ' ' << _a; //prints main's a, followed by somethingThatWillBe_a
}, somethingThatWillBe_a};

If you're just trying to use main's a, it's already captured:

std::thread _testThread{[a] {
    std::cout << a; //prints main's a
}};

I would also recommend being super careful if you think you need to detach a thread. If there's any possibility of joining the thread instead, go for it.

chris
  • 60,560
  • 13
  • 143
  • 205
4

You can access int a in one of two ways. Either pass it in as a parameter to the thread's constructor or capture it in the lambda's closure:

int a=10;

// pass in a as a parameter
std::thread _testThread1([](int _a){

  //do stuff using a or _a ?

}, a); // pass a to the parameter _a
_testThread1.detach();

// capture a in the closure
std::thread _testThread2([a](){ // capture a

  //do stuff using a or _a ?

});
_testThread2.detach();
Galik
  • 47,303
  • 4
  • 80
  • 117
2

If you only want to pass some value to lambda function, look at my code below:

int main()
{
    int a = 10;

    [](int arg)
    {
        cout << "arg = " << arg << endl;
    }
    (a);

    return 0;
}

If you want to make thread with lambda function and passing to it some arguments see next code example:

int main()
{
    int a = 10;

    thread thd([](int arg) { cout << "arg = " << arg << endl; }, a);

    thd.join();

    return 0;
}
Dakorn
  • 883
  • 6
  • 11