如何取消升级asio io_service帖子 [英] How to cancel boost asio io_service post
问题描述
如何取消已发布的回调:
getIoService() - & MyClass :: myCallback,this));
并保持其他已发布的回调不变?
问题是,我有一些对象从不同的线程接收事件,我发布他们到ioservice为了处理主线程中的事件。如果在某个时候我想删除我的对象 - ioservice将尝试执行已经发布的回调在被销毁的对象。在这种情况下,我不能在对象中存储任何标志,因为它将被删除。
有一个可能的解决方案使用 enable_shared_from_this
和
您不能通过 io_service
以这种方式选择性地取消回调。一个选项是将逻辑移动到更高的级别,例如 MyClass
内。示例实现可以是:
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
队列中,在分派之前。
How can I cancel already posted callback:
getIoService()->post(boost::bind(&MyClass::myCallback, this));
and keep other posted callbacks untouched?
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.
There is a possible solution to use enable_shared_from_this
and shared_from_this()
, but wondering whether another solution or not.
Thanks
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;
};
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屋!