1. 程式人生 > >[Chromium]怎樣安全的使用PostTask

[Chromium]怎樣安全的使用PostTask

www. cti 一個 src tools 技術 tails -m lean

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對對象全部權更完整的解釋



[Chromium]怎樣安全的使用PostTask