如何明确其已经在排队的所有发布的任务io_service::strand
? 我看到升压文件没有类似的方法。
Answer 1:
我还没有找到需要它,因为它可以正确地适当地设计异步调用链来解决。 一般来说,Boost.Asio的API是经过精心设计的,它可以防止复杂的应用程序从异步流程变得复杂这样的方式。
如果您已检查调用链,并且是绝对肯定的是,重新设计他们的努力是更大的当前和未来的风险比引进清除链的复杂性,那么还有一个办法来完成它。 然而,它确实有删除内的所有未调用处理程序的主要副作用strand
及其相关io_service
。
当strand
被破坏,它的析构函数时间表未调用处理程序上的递延调用io_service
维护非并发的保证。 该io_service
的析构函数被安排延期调用该是未调用处理程序对象的状态被破坏。 因此,通过控制一个的寿命strand
和io_service
,可以在链清除处理程序。
下面是一个简化的过于例如用一个辅助类clearable_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_;
};
为了使得只有最小化的效果strand
的处理程序被破坏,所述类使用内部io_service
,而不是附接strand
主io_service
。 当工作发布到strand
,处理程序,然后发布到主io_service
将菊花链和服务在本地io_service
。
而它的用法:
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();
}
运行程序将输出1
和4
。 我想强调,这是一个过于简单的例子,在一个非复杂的方式提供线程安全的,以匹配的boost::asio::strand
可以是一个挑战。
Answer 2:
这是不可能的,你需要根据自己的目标来调整你的设计。 一种可能性是充分利用优先处理程序例如 ,如果你的愿望一定高优先级的处理程序之前于低优先级运行。
文章来源: How do it clear all posted tasks which already queued in a strand?