Rony Cohen Rony Cohen - 1 month ago 22
C++ Question

Threading with a for loop

I want to create a for loop from 0 to 4 but my problem is I know only how to initiate one thread each time like this.

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


So my question is how can I initiate many thread at a time in a loop ?

Answer

You can do the following to just build them in-place in a vector1:

std::vector<std::thread> ts;

for (int i = 5; i > 0; --i)
  ts.emplace_back(eat, "hello");

1 Reserving the memory in advance (assuming you know how much) can also be good.

Comments