Why is an acquire barrier needed before deleting the data in an atomically reference counted smart pointer?

后端 未结 3 1483
不知归路
不知归路 2021-02-08 05:08

Boost provides a sample atomically reference counted shared pointer

Here is the relevant code snippet and the explanation for the various orderings used:



        
3条回答
  •  日久生厌
    2021-02-08 05:15

    Consider two threads, each holding one reference to the object, which are the last two references:

    ------------------------------------------------------------
            Thread 1                              Thread 2
    ------------------------------------------------------------
       // play with x here
    
       fetch_sub(...)                            
                                                fetch_sub(...)
       // nothing
                                                delete x;
    

    You have to ensure that any changes made to the object by Thread 1 in //play with x here is visible to Thread 2 when it calls delete x;. For this you need an acquire fence, which, together with the memory_order_release on the fetch_sub() calls, guarantees that the changes made by Thread 1 will be visible.

提交回复
热议问题