Initialization of local static mutex
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Initialization of local static mutex



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. ..."

Does this mean, the compiler is allowed to emit code to initialize
the mutex variable at runtime, after "any other initializations
have taken place" and before "block is entered"?

If this is true, there would be a race condition for the code
that performs this runtime assignment.

I am hoping that I misunderstand the standard here, and that
the above is indeed thread-safe.

Regards,
Roland