Boost::asio,共享内存和进程间通信

Boost::asio, Shared Memory and Interprocess Communication

本文关键字:进程间通信 内存 asio Boost 共享      更新时间:2023-10-16

我有一个应用程序,它专门使用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 post? 假设中断线程完全由来自外部应用程序的计时驱动(通过信号量通知数据可用)。 此外,假设我们可以完全控制消费和提供应用程序,我们有其他对象需要由input_thread对象处理(因此我们不能简单地阻止和等待那里的信号量对象)。 目标是减少通过共享内存提供应用程序传入的数据的开销、CPU 利用率和延迟。

我想自从你发布这个问题以来,你已经找到了答案,这是为了别人的利益......

尝试查看助推股。

它使您能够选择要在哪个线程上执行一些工作。

它将自动在特定链上排队,这是您不必考虑的事情。

如果您需要知道工作何时完成,它甚至会为您提供一个完成处理程序。