Answer the question
In order to leave comments, you need to log in
Is a C++ static function thread-safe?
static inline Settings& applicationSettings(){
if (!File::exists(settingsFilePath)){
static Settings set(settingsFilePath);
set.initializeDefaults();
return set;
}else{
static Settings set(settingsFilePath);
return set;
}
}
Answer the question
In order to leave comments, you need to log in
Make a factory function that checks for the existence of the file and creates it if needed, and then:
static inline Settings& applicationSettings()
{
static Settings set = getSettings(settingsFilePath);
return set;
}
The C++11 standard guarantees that getSettings will only be called once, regardless of the number of threads pulling applicationSettings. The main thing to remember is that getSettings is not thread safe and don't pull it directly.
1. What do you need two static set variables for?
2. Don't forget, the variable is static and resides in the data segment. So the Settings() constructor will be executed before main is run.
3. The function returns a reference without const. Will the settings change? Yes - almost guaranteed to be dangerous (data structures that are thread-safe by writing are rare and complex). No - return const Settings& and make sure that all Settings fields are also thread-safe to read (usually the answer to this question is yes).
4. Is initializeDefaults() thread-safe? Most probably not.
> Is this function call thread-safe?
There is no definitive answer, most likely not.
> Is File()::exists(settingsFilePath) checked every time the function is called?
Performed.
PS. A function like this is definitely thread-safe - it just doesn't have any objects to race against.
static inline Settings applicationSettings(){
if (!File::exists(settingsFilePath)){
Settings set(settingsFilePath);
set.initializeDefaults();
return set;
}else{
return Settings(settingsFilePath);
}
}
Why would this call be thread safe if you have static variables in your function?
Why shouldn't it be done?
By the way, why do you need two different set static variables?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question