Several threads: catching the moment when they all finish work

时间:2018-02-03 08:49:30

标签: c++ multithreading

I have several threads, I need to catch the moment when they all finish work. How to do it?

for (int i = 1; i < 3; i++) {
   std::thread threads1(countFile, i);
   i++;
   std::thread threads2(countFile, i);
   threads1.detach();
   threads2.detach();
}

// wait until all the threads run out---

// to do next function ob object which uses by threads--

2 个答案:

答案 0 :(得分:1)

Consider creating the std::thread objects outside the for-block and calling join() instead of detach():

// empty (no threads associated to them yet)
std::array<std::thread, 2> threads1, threads2;

for (int i = 0; i < 2; i++) {
   threads1[i] = std::thread(countFile, i+1); // create thread
   i++;
   threads2[i] = std::thread(countFile, i+1); // create thread
}

// ...

// join on all of them
for (int i = 0; i < 2; i++) {
   threads1[i].join();
   threads2[i].join();
}

// at this point all those threads have finished

Not calling detach() implies that the call to join() has to be made before the destructor of the std::thread objects gets called (regardless of whether the thread has already finished or not).

For that reason I placed the std::thread objects out of the for-block. Otherwise, join() would have to be called inside the for-block.

答案 1 :(得分:0)

You need to use join and not detach threads from the main thread.

std::vector<std::thread> th1, th2;


for (int i = 0; i < 2; i++) {
   th1.push_back(std::thread(countFile, i+1));
   i++;
   th2.push_back(std::thread(countFile, i+1));
}

//Join the threads
 for(auto &t : th1){
     assert(t.joinable())//you cannot join otherwise
     t.join();
 }
 for(auto &t : th2){
     assert(t.joinable())//you cannot join otherwise
     t.join();
 }
  • thread.join(): the program blocks at this line until thread finishes. If thread does not finish, your proram is blocked so be careful. Note that if you don't join all thread before the end of the program, you get undefined behaviour
  • thread.detach(): don't use it if you want to join, because you won't be able to do it