Boost::asio,共享内存和进程间通信
Boost::asio, Shared Memory and Interprocess Communication
我有一个应用程序,它专门使用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 利用率和延迟。
我想自从你发布这个问题以来,你已经找到了答案,这是为了别人的利益......
尝试查看助推股。
它使您能够选择要在哪个线程上执行一些工作。
它将自动在特定链上排队,这是您不必考虑的事情。
如果您需要知道工作何时完成,它甚至会为您提供一个完成处理程序。
相关文章:
- 进程间通信堆内存
- Win32 进程间通信分配
- 提升进程间共享内存open_or_create每次都会引发异常
- 提升进程间共享内存删除、权限和输出文件
- Electron应用程序和Win32本机桌面应用程序之间的进程间通信
- 在不违反严格的别名规则的情况下访问进程间共享内存中的对象
- 进程间通信 - C# 和C++.对路径的访问被拒绝
- 基于pthread_mutex的进程间通信不起作用
- Python和C++之间使用本地文件套接字的进程间通信
- 如何在进程间通信中获取其他终结点的进程 ID
- 进程间共享内存的非Boost STL分配器
- 使用物理文本文件的进程间通信
- 为什么进程间共享内存需要sudo
- Mac 上高带宽数据流最有效的进程间通信方法是什么?
- 进程间通信 -- 在共享内存中锁定互斥体
- 进程间通信 CUDA
- 使用COM在Windows上的本地计算机上进行进程间通信
- 具有进程间通信功能的服务器-客户端日志记录体系结构.你知道解决方案吗?
- Boost::asio,共享内存和进程间通信
- 共享内存进程间通信