Are function-local static mutexes thread-safe?

前端 未结 3 711
时光取名叫无心
时光取名叫无心 2020-12-28 12:46

In the following program I attempt the make the print function thread-safe by using a function-local mutex object:

#include 
#in         


        
3条回答
  •  滥情空心
    2020-12-28 13:08

    This is not the same as the linked question for several reasons.

    The linked question is not C++11, but yours is. In C++11 initialization of function-local static variables is always safe. Prior to C++11 it was only safe with some compilers e.g. GCC and Clang default to thread-safe initialization.

    The linked question initializes the reference by calling a function, which is dynamic initialization and happens at run-time. The default constructor for std::mutex is constexpr so your static variable has constant initialization, i.e. the mutex can be initialized at compile-time (or link-time) so there is nothing to do dynamically at runtime. Even if multiple threads call the function concurrently there's nothing they actually need to do before using the mutex.

    Your code is safe (assuming your compiler implements the C++11 rules correctly.)

提交回复
热议问题