double checked locking pattern

前端 未结 2 436
猫巷女王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:09

    No, the memory barrier cannot be moved below the assignment-statement since the memory barrier protects the assignment from upwards migration. From the linked article:

    The first barrier must prevent downwards migration of Singleton’s construction (by another thread); the second barrier must prevent upwards migration of pInstance’s initialization.

    On a side note: The double-checked locking pattens for singletons is only useful if you have huge performance requirements.

    Have you profiled your binaries and observed the singleton access as a bottle-neck? If not chances are you do not need to bother at all with the double-checked locking pattern.

    I recommend using a simple lock.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题