I am trying to understand a potential scenario and whether it is likely to be a problem.
So I have a static function that is currently thread-safe. The function being like so:
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 it in itself thread-safe? The array will be initialized once for the entire duration of the application's life, so once the function thread_safe_func() has been called, and fully run, I would expect this to be thread-safe.
The issue is obviously what could occur during the first calls, what would happen in a scenario where a thread calls thread_safe_func(), the initialization of the const array occurs, but before that initialization completes, another thread is calling thread_safe_func().
Would a change to:
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
}
be worthwhile and guarantee that this code is now thread-safe?