【发布时间】: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_n,see it live。 -
@WhozCraig 好的,谢谢。
标签: c++ multithreading c++11 stl