[Chromium]如何安全的使用PostTask

PostTask参数决策树



如何传递绑定的对象

官方的解释总是最权威,有疑问看这里或者直接看代码中的说明: bind_helpers.h. 

传值方式描述
this 或 对象指针

如果对象本身是一个RefCountedThreadSafe, 没有问题.

如果是个裸指针,应当尽量避免,除非你可以保证它的线程安全.

base::Unretained

注意:使用这个的前提是有其它同步机制保障对象的生命周期.

  1. 如果有其它同步机制保障对象的生命周期,可以使用Unretained()传递非引用计数的对象.
  2. 如果是一个非引用计数的对象,可以使用Unretained()封装起来.
base::Owned

如果是临时对象,或者担心任务执行完成后对象可能出现泄露,可以使用Owned, 表示由Task

持有对象的所有权,在结束时析构它.

base::Passed如果要执行Task需要传入scoped指针,就可以使用它转换,它也可以避免拷贝,而是类似move语义.
base::ConstRef类似常量引用,不希望bind过程出现拷贝,就可以使用它.
base::IgnoreResult如果Task要调用的方法带有返回值,而你又不关心返回值就可以使用IgnoreResult来传入对象指针.

 

讨论:为什么要避免引用计数?

如果这样一直将以引用计数来使用对象岂不最为简单,为什么要避免引用计数?

Chromium智能指针指引中的解释:

  • Reference-counted objects make it difficult to understand ownership and destruction order, especially when multiple threads are involved. There is almost always another way to design your object hierarchy to avoid refcounting. Avoiding refcounting in multithreaded situations is usually easier if you restrict each class to operating on just one thread, and use PostTask() and the like to proxy calls to the correct thread. base::Bind(), WeakPtr, and other tools make it possible to automatically cancel calls to such an object when it dies. Note that too much of our existing code uses refcounting, so just because you see existing code doing it does not mean it's the right solution. (Bonus points if you're able to clean up such cases.)

还可以参考: 谨慎使用智能指针

参考

关于Callback和Bind对对象所有权更完整的解释



  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值