I have and Application which has a singleton that stores information across the whole app. However, this is creating some data race issues when using the singleton from different threads.
Here there is a very dummy and simplistic version of the problem:
Singleton
class Singleton {
static var shared = Singleton()
var foo: String = "foo"
}
Use of the singleton (from the AppDelegate for simplicity)
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
DispatchQueue.global().async {
var foo = Singleton.shared.foo // Causes data race
}
DispatchQueue.global().async {
Singleton.shared.foo = "bar" // Causes data race
}
return true
}
}
Is there any way to ensure that a singleton is thread safe, so it can be used from anywhere in the app without having to worry about which thread you are in?
This question is not a duplicate of Using a dispatch_once singleton model in Swift since (if I understood it correctly) in there they are addressing the problem of accessing to the singleton object itself, but not ensuring that the reading and writing of its properties is done thread safely.