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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.