Is C++ static member variable initialization thread-safe?

爱⌒轻易说出口 提交于 2019-11-27 12:06:53

It's more a question of function-scoped static variables vs. every other kind of static variable, rather than scoped vs. globals.

All non-function-scope static variables are constructed before main(), while there is only one active thread. Function-scope static variables are constructed the first time their containing function is called. The standard is silent on the question of how function-level statics are constructed when the function is called on multiple threads. However, every implementation I've worked with uses a lock around the constructor (with a twice-checked flag) to guarantee thread-safety.

Yes(*). When global statics are initialized, there is only one thread around and all constructors are called on it. This is not true for function's statics, though.

(*) One can possibly make global statics not thread-safe by creating threads in some of the constructors and scheduling some initialization stages on these threads. In this case usual thread safety rules apply.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!