Rony Cohen Rony Cohen - 1 year ago 145
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download