c – 如何使用boost :: latch?
发布时间:2020-12-16 06:54:04 所属栏目:百科 来源:网络整理
导读:我试图在我的程序中使用boost :: latch来阻止等待,直到所有线程完成或超时.我的代码如下. ctpl是从 https://github.com/vit-vit/CTPL开始采用的线程池库. #include boost/thread/latch.hpp#include CTPL/ctpl.h#include mutex#include iostreamusing namespa
我试图在我的程序中使用boost :: latch来阻止等待,直到所有线程完成或超时.我的代码如下. ctpl是从
https://github.com/vit-vit/CTPL开始采用的线程池库.
#include <boost/thread/latch.hpp> #include <CTPL/ctpl.h> #include <mutex> #include <iostream> using namespace std; int main(int argc,char **argv) { ctpl::thread_pool outer_tp(100); ctpl::thread_pool inner_tp(5,5000); auto out_func = [&inner_tp](int outer_id,int outer_invoke_idx) { int num_batch = 20; boost::latch latch_(num_batch); auto func = [&latch_,&outer_invoke_idx](int inner_id,int inner_invoke_idx) { try { std::cout << "outer: " << outer_invoke_idx << ",inner: " << inner_invoke_idx << endl; } catch (exception &ex) { cout << "error: " << ex.what() << endl; } latch_.count_down(); }; for (int i = 0; i < num_batch; ++i) { inner_tp.push(func,i); } latch_.wait_for(boost::chrono::milliseconds(1)); }; for (int i = 0; i < 5000; ++i) outer_tp.push(out_func,i); outer_tp.stop(true); return 0; }
但是,我收到以下错误消息.
如果我使用latch_.wait()而不是latch_.wait_for()或设置很长的等待时间,代码可以正常工作.因此,我猜“超时”会导致此错误问题.有没有人知道如何修复错误. 解决方法
您的代码似乎没有什么问题.我认为通过引用引用内部线程中的latch_是其中之一.用shared_ptr替换为boost :: latch修复了那个问题.另一个问题类似于outer_invoke_idx.修复这些并等待inner_tp完成似乎使您的测试工作正常.
这是修改后的测试用例,对我有用: #include <boost/thread/latch.hpp> #include <memory> #include <CTPL/ctpl.h> #include <mutex> #include <iostream> using namespace std; int main(int argc,int outer_invoke_idx) { int num_batch = 20; auto latch_ = std::make_shared<boost::latch>(num_batch); auto func = [latch_,outer_invoke_idx](int inner_id,inner: " << inner_invoke_idx << endl; } catch (exception &ex) { cout << "error: " << ex.what() << endl; } latch_->count_down(); }; for (int i = 0; i < num_batch; ++i) { inner_tp.push(func,i); } latch_->wait_for(boost::chrono::milliseconds(1)); }; for (int i = 0; i < 5000; ++i) outer_tp.push(out_func,i); outer_tp.stop(true); inner_tp.stop(true); std::cout << "EXITING!!!" << std::endl; return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |