Consider creating std::threadobjects off- forblock and calling join()instead detach():
std::array<std::thread, 2> threads1, threads2;
for (int i = 0; i < 2; i++) {
threads1[i] = std::thread(countFile, i+1);
i++;
threads2[i] = std::thread(countFile, i+1);
}
for (int i = 0; i < 2; i++) {
threads1[i].join();
threads2[i].join();
}
Not calling detach()means that the call join()must be made before the called object destructor std::thread(regardless of whether the thread is completed or not).
For this reason, I put objects std::threadfrom for-block. Otherwise, join()it would be necessary to call inside the for-block.
source
share