double checked locking pattern

前端 未结 2 435
猫巷女王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.

提交回复
热议问题