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

tem*_*boy 5 c++ multithreading stl c++11

我试图让它做到我不能从循环中调用线程.但是当我运行它时,我得到一个运行时错误:

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();
}
Run Code Online (Sandbox Code Playgroud)

Bil*_*nch 12

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

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

for (int i=1; i<threads.size(); ++i)
    assert(threads[i - 1].get() == threads[i].get());
Run Code Online (Sandbox Code Playgroud)

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

std::vector<std::shared_ptr<std::thread>> threads(20);
for (auto & thread : threads)
    thread = std::make_shared<std::thread>(foo);
Run Code Online (Sandbox Code Playgroud)

  • 哦,你是对的.你应该在答案中指出这一点.关键的见解是`make_shared`只被调用一次. (2认同)