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?