c – 几个线程:抓住他们都完成工作的那一刻
发布时间:2020-12-16 07:22:40 所属栏目:百科 来源:网络整理
导读:我有几个线程,我需要抓住他们都完成工作的那一刻. 怎么做? 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---//
我有几个线程,我需要抓住他们都完成工作的那一刻.
怎么做? 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(). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |