c – 几个线程:抓住他们都完成工作的那一刻

我有几个线程,我需要抓住他们都完成工作的那一刻.

怎么做?

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--

最佳答案 考虑在for-block之外创建std :: thread对象并调用join()而不是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

不调用detach()意味着必须在调用std :: thread对象的析构函数之前调用join()(无论线程是否已经完成).

出于这个原因,我将std :: thread对象放在for-block之外.否则,必须在for-block内调用join().

点赞