Cha*_*had 11 c++ boost boost-asio boost-interprocess
我有一个应用程序,它被编写为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);
}
}
Run Code Online (Sandbox Code Playgroud)
是否有任何方法可以input_thread直接处理数据(无需post通过interrupt_thread?)假设中断线程完全由来自外部应用程序的时序驱动(通过信号量获得数据的通知).此外,假设我们完全控制了消费和提供应用程序,我们还有其他需要由input_thread对象处理的对象(所以我们不能简单地阻塞并等待那里的信号量对象).目标是减少开销,通过共享内存提供应用程序进入的数据的CPU利用率和延迟.