我有一个应用程序专门使用 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 利用率和通过提供应用程序的共享内存传入的数据的延迟.
最佳答案
我猜你在发布这个问题后已经找到了答案,这是为了其他人的利益...
尝试查看 boost strands .
它使您能够选择要在哪个线程上进行一些工作。
它会自动在特定的链上排队,这是您不必考虑的事情。
如果您需要知道工作何时完成,它甚至会为您提供一个完成处理程序。
关于c++ - Boost::asio、共享内存和进程间通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10145390/