double checked locking pattern

前端 未结 2 431
猫巷女王i
猫巷女王i 2021-02-05 19:47

In C++ and the Perils of Double-Checked Locking, there\'s persudo code to implement the pattern correctly which is suggested by the authors. See below,

Singleton         


        
2条回答
  •  再見小時候
    2021-02-05 20:16

    I didn't see any correct answer here related to your question so I decide to post one even after more than three years;)

    I just wonder that whether the first memory barrier can be moved right above the return statement?

    Yes, it can.

    It's for threads that won't enter the if statement, i.e., pInstance has already been constructed and initialized correctly, and is visible.

    The second barrier (the one right before pInstance = tmp;) guarantees that the initialization of singleton's members fields are committed to memory before pInstance = tmp; is committed. But this does NOT necessarily mean that other threads (on other cores) will see these memory effects in the same order (counter-intuitive, right?). A second thread may see the new value of the pointer in cache but not those member fields yet. When it accesses a member by dereferencing the pointer (e.g., p->data), the address of that member may has already been in cache, but not the one that's desired. Bang! A wrong data is read. Note that this is more than theoretical. There are systems that you need perform a cache coherence instruction (e.g., a memory barrier) to pull new data from memory.

    That's why the first barrier is there. It also explains why it's ok to place it right before the return statement (but it has to be after Singleton* tmp = pInstance;).

    It says that the second barrier doesn't need to be bidirectional, so how can it prevent the assignment to pInstance from being moved before that barrier?

    A write barrier guarantees that every write preceding it will effectively happen before every write following it. It's a stop sign, and no write can cross it to the other side. For a more detailed description, refer to here.

提交回复
热议问题