Local Static variable initialization is thread safe [duplicate]

梦想与她 提交于 2019-12-06 13:52:21

Yes, it will be thread safe, but only since C++11. Static variables are initialized in thread safe way, they are often also called magic statics.

For more see here: http://en.cppreference.com/w/cpp/language/storage_duration#Static_local_variables

If multiple threads attempt to initialize the same static local variable concurrently, the initialization occurs exactly once (similar behavior can be obtained for arbitrary functions with std::call_once). Note: usual implementations of this feature use variants of the double-checked locking pattern, which reduces runtime overhead for already-initialized local statics to a single non-atomic boolean comparison.

Also - in your code you call CreateEmployee(); during initialization of static i, and CreateEmployee( also initializes a static variable. This should also be OK, you can find in standard following footnote:

The implementation must not introduce any deadlock around execution of the initializer.

As to your second question, from the code you have shown I dont see that it is OK to use static variable as a way to gain thread safety.

Are you aware that specifying a variable as static inside function body allows you to assign it only once? This means your CreateEmployee() will always return the same Employee instance.

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