【发布时间】:2012-04-13 17:21:43
【问题描述】:
我有一个应用程序,它专门使用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 中处理数据(而不必通过post 它通过interrupt_thread?假设中断线程完全由来自外部应用程序的时间驱动(通过信号量通知数据可用)。另外,假设我们可以完全控制消费和提供应用程序,我们还有其他需要由input_thread 对象处理的对象(所以我们不能简单地阻塞和等待信号量对象)。目标是减少通过共享内存提供应用程序传入的数据的开销、CPU 利用率和延迟。
【问题讨论】:
-
如果您在 *NIX 上,最简单的方法是使用 UNIX 管道进行通知,因此管道的一端作为常规套接字添加到
input_thread。您仍然会产生同步等开销,但会保存一个冗余副本(到/从套接字缓冲区)。您可以通过套接字发送偏移量和长度,然后直接索引 shmem。 -
在 Windows 中,您可以使用 windows::object_handle 直接在同步对象上进行异步等待。
标签: c++ boost boost-asio boost-interprocess