怎么做?
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 – 几个线程:抓住他们都完成工作的那一刻所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)