首页 技术 正文
技术 2022年11月13日
0 收藏 417 点赞 4,443 浏览 1314 个字

<!–?

xml version=”1.0″ encoding=”UTF-8″ standalone=”no”?–>

PostTask參数决策树

[Chromium]怎样安全的使用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对对象全部权更完整的解释

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,494
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,908
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,133
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,297