为什么这个简单的线程代码失败了?

时间:2014-06-11 17:39:31

标签: c++ multithreading c++11 stl

我试图做到这一点,我无法从循环中调用线程。但是当我运行它时,我得到一个运行时错误:

  

terminate called after throwing an instance of 'std::system_error'
what(): Invalid argument Thread #1

#include <iostream>
#include <vector>
#include <memory>
#include <thread>
#include <mutex>

std::mutex m;
static int thread_count;

auto foo = [&] {
    std::lock_guard<std::mutex> lock(m);
    std::cout << "Thread #" << ++thread_count << std::endl;
};

int main()
{
    std::vector<std::shared_ptr<std::thread>>
             threads(20, std::make_shared<std::thread>(foo));

    for (const auto& th : threads)
        th->join();
}

1 个答案:

答案 0 :(得分:12)

您的代码实际上只创建了一个子线程,因此它在该一个线程上调用了join() 20次。

要验证这一点,您可以在构造向量后立即添加以下循环:

for (int i=1; i<threads.size(); ++i)
    assert(threads[i - 1].get() == threads[i].get());

您可能希望以某种形式创建矢量:

std::vector<std::shared_ptr<std::thread>> threads(20);
for (auto & thread : threads)
    thread = std::make_shared<std::thread>(foo);