我正试图做到这一点,我不能从循环中调用线程。但是当我运行它时,我得到一个运行时错误:
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/