C++;具有lambda函数的线程 我用LAMBDA函数学习C++ STD线程。在下面的示例中,我不知道为什么每个的的第三个参数(lambda)必须使用std::thread&t作为其参数 #include <iostream> #include <thread> #include <vector> #include <algorithm> int main() { // vector container stores threads std::vector<std::thread> workers; for (int i = 0; i < 5; i++) { workers.push_back(std::thread([]() { std::cout << "thread function\n"; })); } std::cout << "main thread\n"; std::for_each(workers.begin(), workers.end(), [](std::thread &t) { t.join(); }); return 0; }

C++;具有lambda函数的线程 我用LAMBDA函数学习C++ STD线程。在下面的示例中,我不知道为什么每个的的第三个参数(lambda)必须使用std::thread&t作为其参数 #include <iostream> #include <thread> #include <vector> #include <algorithm> int main() { // vector container stores threads std::vector<std::thread> workers; for (int i = 0; i < 5; i++) { workers.push_back(std::thread([]() { std::cout << "thread function\n"; })); } std::cout << "main thread\n"; std::for_each(workers.begin(), workers.end(), [](std::thread &t) { t.join(); }); return 0; },c++,C++,我还检查了在我的示例中,如果我将std::thread替换为int,那么使用int t作为的第三个参数,每个也可以工作 std::for_each(workers.begin(), workers.end(), [](std::thread &t) { t.join(); }); 可以翻译成 for (auto it = workers.begin(), end = workers.end(); it != end; ++it) { std::thread &

我还检查了在我的示例中,如果我将
std::thread
替换为
int
,那么使用
int t
作为
的第三个参数,每个
也可以工作

std::for_each(workers.begin(), workers.end(), [](std::thread &t) 
{
    t.join();
});
可以翻译成

for (auto it = workers.begin(), end = workers.end(); it != end; ++it)
{
    std::thread &t = *it; // take a reference to the element, this is fine
    t.join();
}
当您省略
并按值获取线程时,您将得到

for (auto it = workers.begin(), end = workers.end(); it != end; ++it)
{
    std::thread t = *it; // make a copy of the element, boom
    t.join();
}
您创建了一个副本,但无法复制
std::thread
,因此会出现错误。对于手动循环,您可以使用
std::move
like“修复”它

for (auto it = workers.begin(), end = workers.end(); it != end; ++it)
{
    std::thread t = std::move(*it); // now we move into t
    t.join();
}
您可以在
std::for_each
中通过使用like获得相同的行为


为了影响.join(),您必须能够更改作为当前业务主题的向量的元素。由于向量自然是按值作为参数传递的(与数组作为参数传递的方式相反),因此必须使用引用运算符(&)通过引用传递它们。它真的很简单…不要想太多…而且,线程是不可复制构造的。
for (auto it = workers.begin(), end = workers.end(); it != end; ++it)
{
    std::thread t = std::move(*it); // now we move into t
    t.join();
}
std::for_each(std::make_move_iterator(workers.begin()),
              std::make_move_iterator(workers.end()), 
              [](std::thread t) 
{
    t.join();
});