How should I use thread_pool in this case?

for example: when I write this code I recieve right result.

boost::asio::thread_pool t(3);
std::vector<int> vec = {10,20,30};
boost::asio::post(t, [&]{ foo(vec[0]);});
boost::asio::post(t, [&]{ foo(vec[1]);});
boost::asio::post(t, [&]{ foo(vec[2]);});

but when i want use boost::asio::post in for-cicle i recieve error Microsoft Visual C++ Runtime Library:
"Expression: vector subscript out of range"

boost::asio::thread_pool t(3);
std::vector<int> vec = {10,20,30};
for (int i = 0; i < 3; ++i) {
    boost::asio::post(t, [&]{ foo(vec[i]);});

what can i do to make my last way return the correct answer?

>Solution :

You are capturing i by reference for a lambda that is used asynchronously. When t.join(); is reached, i is a dangling reference.

Capture it by value so it doesn’t change or expire.

boost::asio::post(t, [i,&]{ foo(vec[i]);});

Leave a Reply