使用Boost Asio设置发布队列大小限制吗? [英] Setting limit on post queue size with Boost Asio?

查看:121
本文介绍了使用Boost Asio设置发布队列大小限制吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用boost::asio::io_service作为基本线程池.一些线程被添加到io_service,主线程开始发布处理程序,辅助线程开始运行处理程序,并且一切都完成了.到目前为止,一切都很好;与单线程代码相比,我得到了很好的加速.

I'm using boost::asio::io_service as a basic thread pool. Some threads get added to io_service, the main thread starts posting handlers, the worker threads start running the handlers, and everything finishes. So far, so good; I get a nice speedup over single-threaded code.

但是,主线程有数以百万计的东西要发布.而且它只是不断地发布它们,这比工作线程处理它们的速度快得多.我没有达到RAM限制,但是要排队那么多事情还是很愚蠢的.我想做的是为处理程序队列设置一个固定大小,如果队列已满,则设置post()块.

However, the main thread has millions of things to post. And it just keeps on posting them, much faster than the worker threads can handle them. I don't hit RAM limits, but it's still kind of silly to be enqueuing so many things. What I'd like to do is have a fixed-size for the handler queue, and have post() block if the queue is full.

我在Boost ASIO文档中没有看到任何此选项.这可能吗?

I don't see any options for this in the Boost ASIO docs. Is this possible?

推荐答案

我正在使用信号量来修复处理程序队列大小.以下代码说明了此解决方案:

I'm using the semaphore to fix the handlers queue size. The following code illustrate this solution:

void Schedule(boost::function<void()> function)
{
    semaphore.wait();
    io_service.post(boost::bind(&TaskWrapper, function));
}

void TaskWrapper(boost::function<void()> &function)
{
    function();
    semaphore.post();
}

这篇关于使用Boost Asio设置发布队列大小限制吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆