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().

相关文章

一.C语言中的static关键字 在C语言中,static可以用来修饰局...
浅谈C/C++中的指针和数组(二) 前面已经讨论了指针...
浅谈C/C++中的指针和数组(一)指针是C/C++...
从两个例子分析C语言的声明 在读《C专家编程》一书的第三章时...
C语言文件操作解析(一)在讨论C语言文件操作之前,先了解一下...
C语言文件操作解析(三) 在前面已经讨论了文件打开操作,下面...