如何取消升压ASIO io_service对象后 [英] How to cancel boost asio io_service post

查看:148
本文介绍了如何取消升压ASIO io_service对象后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能取消已经发布的回调:

How can I cancel already posted callback:

getIoService()->post(boost::bind(&MyClass::myCallback, this));

和其他保留贴回调不变?

and keep other posted callbacks untouched?

问题是,我有不同的线程接收事件的一些对象,我张贴,以便处理主线程事件的IOService。如果在某些时候我想删除我的对象是什么 - IOService的将尝试执行已张贴在销毁的对象回调。在这种情况下,我不能任何标志存储在对象,因为它会被删除。

The problem is that I have some object that receives events from different thread and I post them to ioservice in order to handle events in main thread. What if at some point I want to delete my object - ioservice will try to execute already posted callbacks in destroyed object. And in this case I can't store any flag in object since it will be removed.

有一个可能的解决方案使用 enable_shared_from_this shared_from_this(),但不知道是否另一种解决方案或没有。

There is a possible solution to use enable_shared_from_this and shared_from_this(), but wondering whether another solution or not.

感谢

推荐答案

通过 io_service对象不能有选择地取消这种方式回调。一种选择是逻辑移动到一个更高的层次,如 MyClass的内部。示例实现可能是:

You cannot selectively cancel callbacks in such a manner through an io_service. One option is to move the logic to a higher level, such as inside of MyClass. A sample implementation may be:

class MyClass : public boost::enable_shared_from_this<MyClass>
{
public:
    typedef boost::shared_ptr<MyClas> Ptr;
    static Ptr create( boost::asio::io_service& io_service ) { 
        const Ptr result( new MyClass );
        io_service.post( boost::bind(&MyClass::myCallback, result) );
        return result;
    }

    void myCallback() { 
        if ( _canceled ) return;
    }

    void cancel() { _canceled = true; }

private:
    MyClass() : _canceled(false) { }

private:
    bool _canceled;
};

本类使用的boost :: shared_ptr的实施共享所有权的语义。这样做gurantees的对象的生命周期将持续,只要回调分派之前保留在 io_service对象队列。

This class uses a boost::shared_ptr to enforce shared ownership semantics. Doing this gurantees the object lifetime will persist as long as the callback remains in the io_service queue before being dispatched.

这篇关于如何取消升压ASIO io_service对象后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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