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

Why does this simple thread code fail?

本文关键字:代码 失败 线程 简单 为什么      更新时间:2023-10-16

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

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();
}

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

为了验证这一点,可以在构造vector之后添加以下循环:
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);