简体   繁体   English

在这种情况下我应该如何使用 thread_pool?

[英]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"但是当我想在 for-cicle 中使用 boost::asio::post 时,我收到错误 Microsoft Visual C++ 运行时库:“表达式:向量下标超出范围”

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?我该怎么做才能让我的最后一种方式返回正确答案?

You are capturing i by reference for a lambda that is used asynchronously.您正在通过引用捕获i以获取异步使用的 lambda。 When t.join();t.join(); is reached, i is a dangling reference .达到, i是一个悬空的参考

Capture it by value so it doesn't change or expire.按值捕获它,使其不会更改或过期。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM