Thread-safe initialization of function-local static const objects

后端 未结 8 1466
悲&欢浪女
悲&欢浪女 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条回答
  •  旧时难觅i
    2020-12-28 16:45

    In brief, I think that:

    • The object initialization is thread-safe, assuming that "some_mutex" is fully constructed when entering "create_const_thingy".

    • The initialization of the object reference inside "use_const_thingy" is not guaranteed to be thread-safe; it might (as you say) be subject of getting initialized multiple times (which is less of a problem), but it might also be subject to word tearing which could result in undefined behaviour.

    [I assume that the C++ reference is implemented as a reference to the actual object using a pointer value, which could in theory be read when partially written to].

    So, to try and answer your question:

    1. Safe enough in practice: Very likely, but ultimately depends on pointer size, processor architecture and code generated by the compiler. The crux here is likely to be whether a pointer-sized write/read is atomic or not.

    2. Safe according to the rule: Well, there are no such rules in C++98, sorry (but you knew that already).


    Update: After posting this answer I realized that it only focuses on a small, esoteric part of the real problem, and because of this decided to post another answer instead of editing the contents. I'm leaving the contents "as-is" as it has some relevance to the question (and also to humble myself, reminding me to think through things a bit more before answering).

提交回复
热议问题