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

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

概述我有几个线程,我需要抓住他们都完成工作的那一刻. 怎么做? for (int i = 1; i < 3; i++) { std::thread threads1(countFile, i); i++; std::thread threads2(countFile, i); threads1.detach(); threads2.detach();}// wait 我有几个线程,我需要抓住他们都完成工作的那一刻.
怎么做?

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 themfor (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 – 几个线程:抓住他们都完成工作的那一刻全部内容,希望文章能够帮你解决c – 几个线程:抓住他们都完成工作的那一刻所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1229044.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存