1

I would like to do a for-loop which creates more threads.

I've tried with:

int i;
for (i = 0; i < 10; i++) {
    thread t1(nThre);
    t1.join();
    cout << "Joined thread n'" << i << '\n';
}

But it does not work. nThre is called sequentially (it is a simple void routine).

I'm also asking if I can use a pre-increment as i is just an int, so: ++i insted of i++, which should be more performant.

tforgione
  • 1,234
  • 15
  • 29
Jon Prepe
  • 49
  • 1
  • 1
  • 5

1 Answers1

11

Your problem is that you start a thread, and join it before starting the next one. You should do like this :

int i;
vector<thread> threads;

for (i = 0; i < 10; i++) {
    threads.push_back(thread(nThre));
    cout << "Started thread n'" << i << "\n";
}

for (i = 0; i < 10; i++) {
    threads[i].join();
    cout << "Joined thread n'" << i << "\n";
}

First, you start all your threads, then you wait until they are finished.

For the difference between i++ and ++i, since i is a integer, it makes no difference here. See this answer for more details.

Community
  • 1
  • 1
tforgione
  • 1,234
  • 15
  • 29