Thread safe lazy construction of a singleton in C++

后端 未结 9 1561
梦毁少年i
梦毁少年i 2020-11-29 19:22

Is there a way to implement a singleton object in C++ that is:

  1. Lazily constructed in a thread safe manner (two threads might simultaneously be the first user o
9条回答
  •  一整个雨季
    2020-11-29 19:29

    1. read on weak memory model. It can break double-checked locks and spinlocks. Intel is strong memory model (yet), so on Intel it's easier

    2. carefully use "volatile" to avoid caching of parts the object in registers, otherwise you'll have initialized the object pointer, but not the object itself, and the other thread will crash

    3. the order of static variables initialization versus shared code loading is sometimes not trivial. I've seen cases when the code to destruct an object was already unloaded, so the program crashed on exit

    4. such objects are hard to destroy properly

    In general singletons are hard to do right and hard to debug. It's better to avoid them altogether.

提交回复
热议问题