使用for循环执行线程

Threading with a for loop

本文关键字:线程 执行 循环 for 使用      更新时间:2023-10-16

我想创建一个从0到4的for循环,但我的问题是我只知道如何每次像这样启动一个线程。

thread t1(eat,"hello");
thread t2(eat,"hello");

所以我的问题是如何在一个循环中一次启动多个线程?

您可以执行以下操作来在vector1中构建它们:

std::vector<std::thread> ts;
for (int i = 5; i > 0; --i)
  ts.emplace_back(eat, "hello");

1提前预留内存(假设您知道多少内存)也可以是好的