c – Boost :: asio,共享内存和进程间通信
我有一个应用程序被编写为使用boost :: asio专门作为其输入数据的来源,因为我们的大多数对象是基于网络通信.由于某些特定要求,我们现在需要使用共享内存作为输入法.我已经写了共享内存组件,它的工作相对较好.
问题是如何处理从共享内存进程到消费应用程序的通知,数据可以被读取 – 我们需要处理现有输入线程中的数据(使用boost :: asio),我们也不需要阻止输入线程等待数据. 我已经实现了这一点,引入了一个等待事件的中间线程从共享内存提供程序进程发出信号,然后将一个完成处理程序发送到输入线程来处理数据的读取. 这也是现在工作,但是引入中间线程意味着在大量情况下,我们有一个额外的上下文切换,然后我们可以读取对延迟有负面影响的数据,并且额外的线程的开销也是比较贵 这是应用程序正在做的一个简单的例子: #include <iostream> using namespace std; #include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/scoped_ptr.hpp> #include <boost/bind.hpp> class simple_thread { public: simple_thread(const std::string& name) : name_(name) {} void start() { thread_.reset(new boost::thread( boost::bind(&simple_thread::run,this))); } private: virtual void do_run() = 0; void run() { cout << "Started " << name_ << " thread as: " << thread_->get_id() << "n"; do_run(); } protected: boost::scoped_ptr<boost::thread> thread_; std::string name_; }; class input_thread : public simple_thread { public: input_thread() : simple_thread("Input") {} boost::asio::io_service& svc() { return svc_; } void do_run() { boost::system::error_code e; boost::asio::io_service::work w(svc_); svc_.run(e); } private: boost::asio::io_service svc_; }; struct dot { void operator()() { cout << '.'; } }; class interrupt_thread : public simple_thread { public: interrupt_thread(input_thread& input) : simple_thread("Interrupt"),input_(input) {} void do_run() { do { boost::this_thread::sleep(boost::posix_time::milliseconds(500)); input_.svc().post(dot()); } while(true); } private: input_thread& input_; }; int main() { input_thread inp; interrupt_thread intr(inp); inp.start(); intr.start(); while(true) { Sleep(1000); } } 有没有办法直接在input_thread中处理数据(不必通过interrupt_thread发布)?假设中断线程完全由来自外部应用程序的时间驱动(通过信号量通知数据)另外,假设我们对消费和提供的应用程序都有完全的控制,我们有额外的对象需要被input_thread对象处理(所以我们不能简单地阻止和等待信号量对象),目标是减少通过共享内存提供应用程序进入的数据的开销,CPU利用率和延迟. 解决方法
我想你已经发现了你的答案,因为你发布了这个问题,这是为了别人的好处…
尝试检查boost strands. 它使您能够选择要在哪些线程上进行某些工作. 它会自动在特定的线上排队,这是你不必考虑的. 如果您需要知道工作何时完成,甚至给您一个完成处理程序. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |