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

C++ 为什么这个简单的线程代码会失败?,c++,multithreading,c++11,stl,C++,Multithreading,C++11,Stl,我正在努力做到不能从循环中调用线程。但当我运行它时,我会得到一个运行时错误: 在抛出“std::system\u error”实例后终止调用 what():无效参数 线程#1 #包括 #包括 #包括 #包括 #包括 std::互斥m; 静态int线程计数; 自动foo=[&]{ 标准:锁和防护锁(m); std::cout您的代码实际上只创建了一个子线程,因此它对该线程调用了20次join() 为了验证这一点,可以在构建向量后立即添加以下循环: for (int i=1; i<thread

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

在抛出“std::system\u error”实例后终止调用
what():无效参数 线程#1

#包括
#包括
#包括
#包括
#包括
std::互斥m;
静态int线程计数;
自动foo=[&]{
标准:锁和防护锁(m);

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

为了验证这一点,可以在构建向量后立即添加以下循环:

for (int i=1; i<threads.size(); ++i)
    assert(threads[i - 1].get() == threads[i].get());

用于(int i=1;在gdb下使用
catch-throw
@sharth是正确的。但是为什么
共享\u ptr
?好吧,在添加
fill
之后,现在发布的代码仍然不正确。你应该使用
std::generate\u n
。@WhozCraig好的谢谢。@DavidSchwartz同一个共享\u ptr的副本有很多e vector.或多个共享的ptr管理同一个对象。哦,你是对的。你应该在答案中指出这一点。关键是
make\u shared
只调用一次。
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);