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

标签 c++ multithreading c++11 stl

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

terminate called after throwing an instance of 'std::system_error'<br/> 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());

您可能希望使用以下形式创建 vector :

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

关于c++ - 为什么这个简单的线程代码会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24169224/

相关文章:

c++ - 静态多态性对实现接口(interface)有意义吗?

c# - 如何在 .NET 3.5 中从 .NET 4 功能实现 Barrier 类

python - 在 python/BeautifulSoup 中进行网络爬行时将值附加到可迭代对象(还想了解多线程)

c++ - 为什么我不能使用带自动的大括号初始化一个值并将它传递给这个函数

c++11 - 带有 boost::adaptor::indexed 的基于范围的 for 循环

c++ - 定义转换构造函数和转换运算符时哪个优先,为什么编译器会对此转换有所不同?

c++ - 作业帮助 : Prime Number Identifier C++

c++ - 错误 C2899 : typename cannot be used outside a template declaration

c# - 从另一个线程读取复选框状态

c++ - std::thread 在使用参数创建时抛出访问冲突异常?