【问题标题】:Why does this simple thread code fail?为什么这个简单的线程代码会失败?
【发布时间】:2014-06-11 17:39:31
【问题描述】:

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

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

【问题讨论】:

  • 使用catch throw在gdb下运行它。
  • @sharth 是对的。但是为什么shared_ptrs
  • 好吧,在添加fill 之后发布的代码仍然不正确。你应该使用std::generate_nsee it live
  • @WhozCraig 好的,谢谢。

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


【解决方案1】:

您的代码实际上只创建了一个子线程,因此它在该线程上调用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);

【讨论】:

  • @DavidSchwartz 向量中有许多相同的 shared_ptr 副本。或者许多 shared_ptrs 管理同一个对象。
  • 哦,你是对的。您应该在答案中指出这一点。关键见解是 make_shared 只被调用一次。
猜你喜欢
  • 1970-01-01
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-06
  • 1970-01-01
相关资源
最近更新 更多