Search code examples
c++c++11stdasync

How can I pass in a variable to a std::async?


How can I pass in a vector to an async call like so??

std::vector<int> vectorofInts;
vectorofInts.push_back(1);
vectorofInts.push_back(2);
vectorofInts.push_back(3);

std::async([=]
{
    //I want to access the vector in here, how do I pass it in
    std::vector<int>::iterator position = std::find(vectorofInts.begin(), vectorofInts.end(), 2);
    //Do something 
}

Solution

  • You're already capturing it by value in the lambda, by specifying [=] as the capture list. So, within the lambda body, you can use vectorofInts to refer to that copy. You could specify [vectorofInts] if you want to be more explicit; just [=] will automatically capture any variable that's used by the lambda.

    However, you can't modify captured values unless the lambda is mutable. So the vector is treated as const, and find returns a const_iterator. As the error message (posted in a comment) says, you can't convert iterator to const_iterator, so change your variable type to std::vector<int>::iterator or auto.

    If you want to access the vector itself, not a copy, then capture by reference by specifying [&], or [&vectorofInts] if you want to be explicit. But be careful what you do with it if you share it between threads like that, and make sure you don't destroy it until the asyncronous access has completed.