C++ atomic 的例子:為何 reference count -1 的時候要用 memory_order_acq_rel

fcamel
1 min readNov 20, 2016

--

這是 Herb Sutter 在 《C++ and Beyond 2012: atomic<> Weapons》介紹的例子:

不懂為何在 -1 的時候要用 memory_order_acq_rel。

在這裡查到說明

Increasing the reference counter can always be done with memory_order_relaxed: New references to an object can only be formed from an existing reference, and passing an existing reference from one thread to another must already provide any required synchronization.

It is important to enforce any possible access to the object in one thread (through an existing reference) to happen before deleting the object in a different thread. This is achieved by a “release” operation after dropping a reference (any access to the object through this reference must obviously happened before), and an “acquire” operation before deleting the object.

It would be possible to use memory_order_acq_rel for the fetch_sub operation, but this results in unneeded "acquire" operations when the reference counter does not yet reach zero and may impose a performance penalty.

在 -1 的時候分兩個情況討論:

  • n > 1: 確保釋放物件前的更新能被其它 thread 看到,需要 release。
  • n = 1: 確保有看到其它 thread 的更新,需要 acquire。

除了演講投影片中提到的例子 (影片中沒有細講),Bootstrap 也有提供一些 atomic 的使用例子。要用的時候,還是多看些例子,看看能否直接拿來用 (C++11 應該和 Bootstrap 的 API 差不多吧,有需要再來確認,還有查其它 C++11 的例子),或是藉此確認觀念正確再來用 atomic。

--

--