About using a static constant variable in a multi-threaded environment

I am trying to understand a potential scenario and whether this could be a problem.

So, I have a static function that is currently thread safe. The function looks like this:

static thread_safe_func() { ... process } 

Now in this function, I add the following:

 static thread_safe_func() { static const Class::NonThreadSafeClassName() *array[16] = { Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), } ... code continues here } 

Now is this thread safe in itself? The array will be initialized once throughout the life of the application, so when the thread_safe_func () function was called and fully launched, I expect it to be thread safe.

The problem is what can happen during the first calls, what happens in the script, when the thread calls thread_safe_func (), the const array is initialized, but before this initialization completes, another thread calls thread_safe_func ().

Will there be a change:

 static ClassMutex lock = ClassMutex() static thread_safe_func() { lock.Lock() static const Class::NonThreadSafeClassName() *array[16] = { Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), Class::NonThreadSafeClassName(), } lock.Unlock() ... code continues here } 

Is it worth it to guarantee that this code is thread safe now?

+6
source share
1 answer

In C ++ 03 , no ...

 void foo() { static your_variable = ...; } 

... neither ...

 void foo() { lock.Lock(); static your_variable = ...; lock.Unlock(); } 

... are thread safe.

The first of them is not thread safe, because the standard does not say anything about the second thread that is part of the function, while the first thread is still initializing. In fact, the standard has no concept of threads at all.

The second is not thread safe, since initialization occurs when a thread of execution enters a function (for the first time), which is before lock.Lock() .


In C ++ 11 , initializing a local static variable is thread safe .

+5
source

Source: https://habr.com/ru/post/909959/


All Articles