Multiple threads: pick up when everyone is done

I have several threads, I need to catch the moment when they 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--
+4
source share
2 answers

Consider creating std::threadobjects off- forblock and calling join()instead 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()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.

+1
source

, .

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(): , . , , . : , undefined
  • thread.detach(): , ,
0

Source: https://habr.com/ru/post/1693110/


All Articles