天天看點

C++核心準則CP.32:使用shared_ptr在無關線程之間共享所有權

CP.32: To share ownership between unrelated threads use shared_ptr

CP.32:使用shared_ptr在無關線程之間共享所有權

Reason(原因)

If threads are unrelated (that is, not known to be in the same scope or one within the lifetime of the other) and they need to share free store memory that needs to be deleted, a shared_ptr (or equivalent) is the only safe way to ensure proper deletion.

如果線程之間沒有關聯(即,無法斷定處于相同的作用域,或者一個線程處于另一個線程的生命周期中)而且共享需要删除的自由存貯記憶體,share_ptr(或等價物)是可以保證安全、正确地銷毀記憶體的唯一方法。

Example(示例)

???      

Note(注意)

  • A static object (e.g. a global) can be shared because it is not owned in the sense that some thread is responsible for its deletion.
  • 沒有任何線程有責任銷毀靜态對象(例如全局變量),從這個角度來講靜态對象是沒有所有者的。是以可以說靜态變量是可以共享的。
  • An object on free store that is never to be deleted can be shared.
  • 存在于永遠不會被銷毀的自由存儲上的對象可以共享。
  • An object owned by one thread can be safely shared with another as long as that second thread doesn't outlive the owner.
  • 隻要第二個線程的生命期間沒有長于所有者線程,那麼一個線程擁有的對象就可以安全的分享給第二個線程。

Enforcement(實施建議)

???

原文連結

​​https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp31-pass-small-amounts-of-data-between-threads-by-value-rather-than-by-reference-or-pointer​​

新書介紹

以下是本人3月份出版的新書,拜托多多關注!

C++核心準則CP.32:使用shared_ptr在無關線程之間共享所有權

本書利用Python 的标準GUI 工具包tkinter,通過可執行的示例對23 個設計模式逐個進行說明。這樣一方面可以使讀者了解真實的軟體開發工作中每個設計模式的運用場景和想要解決的問題;另一方面通過對這些問題的解決過程進行說明,讓讀者明白在編寫代碼時如何判斷使用設計模式的利弊,并合理運用設計模式。

對設計模式感興趣而且希望随學随用的讀者通過本書可以快速跨越從了解到運用的門檻;希望學習Python GUI 程式設計的讀者可以将本書中的示例作為設計和開發的參考;使用Python 語言進行圖像分析、資料處理工作的讀者可以直接以本書中的示例為基礎,迅速建構自己的系統架構。

繼續閱讀