Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]);});
t.join();

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]);});
}
t.join();

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]);});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading