C++0x static initializations and thread safety

最后都变了- 提交于 2019-12-10 02:02:16

问题


I know that as of the C++03 standard, function-scope static initializations are not guaranteed to be thread safe:

void moo()
{
    static std::string cat("argent");  // not thread safe
    ...
}

With the C++0x standard finally providing standard thread support, are function-scope static initializations required to be thread safe?


回答1:


it seems the initialization would be thread safe, since in the case the object is dynamically initialized upon entering the function, it's guaranteed to be executed in a critical section:

§ 6.7 stmt.decl

4. ...such an object is initialized the first time control passes through its declaration... If control enters the declaration concurrently while the object is being initialized, the concurrent execution shall wait for completion of the initialization...

there is a potential edge-case, if after returning from main(), the destructor of a static object calls the function after the static local has already destroyed, the behavior is undefined. however, that should be easy to avoid.



来源:https://stackoverflow.com/questions/1987679/c0x-static-initializations-and-thread-safety

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