繁体   English   中英

具有Lambda函数的C ++线程

[英]C++ thread with lambda function

我正在学习带有lambda函数的C ++ std线程。 在以下示例中,我不知道为什么for_each的第三个参数(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;
}

使用std::thread t ,它给出以下编译错误:

In file included from /usr/include/c++/4.8.2/algorithm:62:0,
                 from foo.cc:6:
/usr/include/c++/4.8.2/bits/stl_algo.h: In instantiation of ‘_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = __gnu_cxx::__normal_iterator<std::thread*, std::vector<std::thread> >; _Funct = main()::__lambda1]’:
foo.cc:20:3:   required from here
/usr/include/c++/4.8.2/bits/stl_algo.h:4417:14: error: use of deleted function ‘std::thread::thread(std::thread&)’
  __f(*__first);
              ^
In file included from foo.cc:2:0:
/usr/include/c++/4.8.2/thread:125:5: error: declared here
     thread(thread&) = delete;
     ^
foo.cc:18:64: error:   initializing argument 1 of ‘main()::__lambda1’
  std::for_each(workers.begin(), workers.end(), [](std::thread t) {

我还检查了是否在示例中将int替换为std::thread ,将int t作为for_each的第三个参数也可以使用。

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来“修复”该问题

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::make_move_iteratorstd::for_each获得相同的行为,例如

std::for_each(std::make_move_iterator(workers.begin()),
              std::make_move_iterator(workers.end()), 
              [](std::thread t) 
{
    t.join();
});

暂无
暂无

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

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