[c++-pthreads] Initialization of local static mutex
Mark Mitchell
mark at codesourcery.com
Sun Oct 8 16:25:16 UTC 2006
Roland Schwarz wrote:
> I am unsure if it is thread safe to use a local
> static mutex in the following manner:
>
> void foo()
> {
> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
> pthread_mutex_loc(&mutex);
>
> ...
>
> pthread_mutex_unlock(&mutex);
> }
>
> I am unsure because the standard says:
>
> 6.7/4:
> "The zero-initialization of all local objects with static
> storage duration is performed before any other initialization
> takes place. A local object of POD type with static storage
> duration initialized with constant-expressions is initialized
> before its block is first entered. ..."
PTHREAD_MUTEX_INITIALIZER is supposed to be a constant-expression (like
"-1" or "{ 1, 0 }"), so the initialization will happen before foo is
called, typically at program start-up.
> I am hoping that I misunderstand the standard here, and that
> the above is indeed thread-safe.
I believe your code is thread-safe in practice for the particular case
of PTHREAD_MUTEX_INITIALIZER.
--
Mark Mitchell
CodeSourcery
mark at codesourcery.com
(650) 331-3385 x713
More information about the c++-pthreads
mailing list