Is initialization of local static function-object thread-safe?

做~自己de王妃 提交于 2019-12-05 23:18:51

问题


The following two functions produce different assemblies, which tells me they're different. Can someone tell me in what way they are different? And is the function local static variable initialization in func2 thread-safe or not? If the answer depends on the compiler, I'd like to know how would the most common compilers behave with func2.

int func1(int val)
{
    const auto impl = [](int v)
    {
        return v * 10;
    };

    return impl(val);
}

int func2(int val)
{
    static const auto impl = [](int v)
    {
        return v * 10;
    };

    return impl(val);
}

回答1:


"The most common compilers" probably differ on this, as they have not all the same support for C++11.

In C++11 the initialization of the static variable is thread safe. In C++03 it is not (as there aren't any threads according to the standard).




回答2:


As Bo says, the current C++ standard demands that static variable initialization not introduce a data race. (This is of course only relevant to the dynamic initialization phase.) For example, if you look at the output of GCC when initializing a static variable, you'll indeed find calls to __cxa_guard_acquire, __cxa_guard_release and __cxa_guard_abort surrounding the initialization.

The Itanium C++ ABI actually formalizes the mechanism.



来源:https://stackoverflow.com/questions/11939484/is-initialization-of-local-static-function-object-thread-safe

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