C++ 如何清除已在链中排队的所有已发布任务?
如何清除已在C++ 如何清除已在链中排队的所有已发布任务?,c++,boost,boost-asio,C++,Boost,Boost Asio,如何清除已在io_服务::strand中排队的所有已发布任务?我在boost文档中没有看到类似的方法。这是不可能的,您需要根据您的目标重新构造设计。如果希望某些高优先级处理程序在低优先级处理程序之前运行,一种可能性是利用。我还没有找到需要它的地方,因为通过正确设计异步调用链可以正确地解决这个问题。通常,Boost.asioAPI是经过精心设计的,它可以防止复杂的应用程序在异步流中变得复杂 如果您已经检查了呼叫链,并且绝对确定重新设计呼叫链的努力比引入清除链的复杂性更大的当前和未来风险,那么有一种
io_服务::strand
中排队的所有已发布任务?我在boost文档中没有看到类似的方法。这是不可能的,您需要根据您的目标重新构造设计。如果希望某些高优先级处理程序在低优先级处理程序之前运行,一种可能性是利用。我还没有找到需要它的地方,因为通过正确设计异步调用链可以正确地解决这个问题。通常,Boost.asioAPI是经过精心设计的,它可以防止复杂的应用程序在异步流中变得复杂
如果您已经检查了呼叫链,并且绝对确定重新设计呼叫链的努力比引入清除链的复杂性更大的当前和未来风险,那么有一种方法可以实现。但是,它确实有一个主要的副作用,那就是删除串
及其关联的io\u服务
中所有未调用的处理程序
当串
被销毁时,它会为io_服务
上的延迟调用调度未调用的处理程序,以保证非并发性。io_服务
声明计划进行延迟调用的未调用处理程序对象将被销毁。因此,通过控制串
和io_服务
的生存期,可以清除串中的处理程序
下面是一个过度简化的示例,其中包含一个helper类clearable\u strand
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/optional.hpp>
#include <boost/utility/in_place_factory.hpp>
class clearable_strand
{
public:
clearable_strand(boost::asio::io_service& main_io_service)
: main_io_service_(main_io_service)
{
clear();
}
public:
template <typename Handler>
void post(const Handler& handler)
{
// Post handler into the local strand.
local_strand_->post(handler);
// Local service now has work, so post its run handler to the
// main service.
main_io_service_.post(boost::bind(
&boost::asio::io_service::run_one, boost::ref(local_io_service_)));
}
void clear()
{
// Destroy previous (if any).
local_strand_ = boost::none;
local_io_service_ = boost::none;
// Reconstruct.
local_io_service_ = boost::in_place();
local_strand_ = boost::in_place(boost::ref(local_io_service_.get()));
}
private:
boost::asio::io_service& main_io_service_;
boost::optional<boost::asio::io_service> local_io_service_;
boost::optional<boost::asio::strand> local_strand_;
};
运行程序将输出
1
和4
。我想强调的是,这是一个过于简化的示例,以一种不复杂的方式提供线程安全性以匹配boost::asio::strand
的安全性可能是一个挑战。这是不可能的。考虑重新设计需要这种功能的模块。完全同意。只是出于好奇。你的优先处理程序示例非常有趣,对我未来的项目非常有帮助。我会把这个加入书签。谢谢,谢谢你的解决方案。
void print(unsigned int x)
{
std::cout << x << std::endl;
}
int main()
{
boost::asio::io_service io_service;
io_service.post(boost::bind(&print, 1));
clearable_strand strand(io_service);
strand.post(boost::bind(&print, 2));
strand.post(boost::bind(&print, 3));
strand.clear(); // Handler 2 and 3 deleted.
strand.post(boost::bind(&print, 4));
io_service.run();
}