Thread-safe initialization of function-local static const objects

后端 未结 8 1496
悲&欢浪女
悲&欢浪女 2020-12-28 16:41

This question made me question a practice I had been following for years.

For thread-safe initialization of function-local static const objects I protect t

8条回答
  •  抹茶落季
    2020-12-28 16:50

    I am not standardista...

    But for the use you mention, why not simply initialize them before any thread is created ? Many Singletons issues are caused because people use the idiomatic "single thread" lazy initialization while they could simply instantiate the value when the library is loaded (like a typical global).

    The lazy fashion only makes sense if you use this value from another 'global'.

    On the other hand, another method I've seen was to use some kind of coordination:

    • 'Singleton' to be register their initialization method in a 'GlobalInitializer' object during library load time
    • 'GlobalInitializer' to be called in 'main' before any thread is launched

    though I may not be describing it accurately.

提交回复
热议问题