【发布时间】:2019-01-30 03:54:47
【问题描述】:
我在多线程 C++ 代码中经常使用 asio::io_service。最近,由于在处理各种任务时缺乏优先级,我发现了我的代码中的一个瓶颈。我自然而然地遇到了这种提升example 以确保某些任务的优先级高于休息。但此示例仅适用于单线程应用程序。
通常,我的代码使用这种模式。
boost::asio::io_service ioService;
boost::thread_group threadPool;
boost::asio::io_service::work work(ioService);
int noOfCores = boost::thread::hardware_concurrency();
for (int i = 0 ; i < noOfCores ; i ++)
{
threadPool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));
}
threadPool.join_all();
我从其他各种线程执行大量 ioService.post(),所有这些处理程序都具有相同的优先级。
现在,如果我要使用 boost 示例中的 handler_priority_queue,首先我必须为 add() 和 execute_all() 函数添加一些互斥保护。
boost::mutex _mtx;
void add(int priority, boost::function<void()> function)
{
boost::lock_guard<boost::mutex> lock(_mtx);
handlers_.push(queued_handler(priority, function));
}
void execute_all()
{
while (!handlers_.empty())
{
boost::unique_lock<boost::mutex> lock(_mtx);
queued_handler handler = handlers_.top();
handlers_.pop();
lock.unlock();
handler.execute();
}
}
但是,我不确定是什么替换了我当前代码中的以下行。
threadPool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));
我显然需要以某种方式将 io_service::run 替换为 handler_priority_queue::execute_all() 。但是怎么做?最好的方法是什么?
我可以这样做...
threadPool.create_thread(boost::bind(&handler_priority_queue::execute_all,
&pri_queue));
但是 execute_all() 马上就出来了。我认为 execute_all() 需要以某种方式重新设计。这个怎么样?它有效,但我不确定其中的陷阱。
void execute_all()
{
while (ioService.run_one())
{
while (ioService.poll_one());
while (true)
{
queued_handler handler;
{
boost::lock_guard<boost::mutex> lock(_mtx);
if (handlers_.empty())
{
break;
}
else
{
handler = handlers_.top();
handlers_.pop();
}
}
handler.execute();
}
}
}
【问题讨论】:
-
我建议您仔细检查更改任务的执行顺序是否可以解决您的性能问题。通常情况下,很难解决简单的解决方案。
-
这不是我在查询中链接的示例吗?我正在尝试实现它的多线程版本。
-
我没有看到那个链接的例子,因为它是一个不透明的链接 :) 很高兴你看到了它
标签: c++ multithreading boost-asio