循环创建线程并加入可变数量的线程

C. *_*ley 5 c++ multithreading loops

我正在构建一个程序,出于测试目的,该程序可以在 C++ 中创建 N 个线程。我是 C++ 的新手,我目前的尝试是

//Create a list of threads
std::vector<std::thread> t;
for(i=0; i < THREADS; i ++){
    std::thread th = std::thread([](){ workThreadProcess(); });
    t.push_back(th);
    printf("Thread started \n");
    }

for(std::thread th : t){
    th.join();
}
Run Code Online (Sandbox Code Playgroud)

我目前有一个错误,提示调用已删除的“std::thread”构造函数。我不知道这是什么意思或如何解决

注意:
我看过:

但我觉得他们没有回答我的问题。他们中的大多数使用 pthreads 或不同的构造函数。

Chr*_*phe 7

你不能复制线程。您需要移动它们才能将它们放入向量中。此外,您不能在循环中创建临时副本来加入它们:您必须改用引用。

这是一个工作版本

std::vector<std::thread> t;
for(int i=0; i < THREADS; i ++){
    std::thread th = std::thread([](){ workThreadProcess(); });
    t.push_back(std::move(th));  //<=== move (after, th doesn't hold it anymore 
    std::cout<<"Thread started"<<std::endl;
    }

for(auto& th : t){              //<=== range-based for uses & reference
    th.join();
}
Run Code Online (Sandbox Code Playgroud)

在线演示

  • 这是对错误的正确解释,但 OP 最好使用 emplace_back,如在 t.emplace_back([] { workThreadProcess(); }); 中,而不是只创建一个 std::thread 对象移动它 (4认同)