Bry*_*Fok 4 c++ boost boost-asio
如何清除已排队的所有已发布任务io_service::strand?我没有看到来自boost文档的类似方法.
我还没有找到它的需要,因为通过正确设计异步调用链可以正确解决它.通常,Boost.Asio API经过精心设计,可以防止复杂的应用程序在异步流程中变得复杂.
如果您已经检查过调用链,并且绝对肯定重新设计它们的努力比引入清除链的复杂性带来更大的当前和未来风险,那么有一种方法可以实现它.但是,它确实具有删除所有未经调用的处理程序strand及其关联的主要副作用io_service.
当a strand被销毁时,它的析构函数会调度uninvoked处理程序以延迟调用,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_;
};
Run Code Online (Sandbox Code Playgroud)
为了最小化效果以便仅strand销毁处理程序,该类使用内部io_service而不是附加strand到main 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();
}
Run Code Online (Sandbox Code Playgroud)
运行程序将输出1和4.我想强调的是,它是一个过于简化的示例,并且以非复杂的方式提供线程安全性以匹配boost::asio::strand可能是一个挑战.
| 归档时间: |
|
| 查看次数: |
3879 次 |
| 最近记录: |