I have a Swift class which uses a traditional Cocoa singleton pattern: one static shared
constant and a private init
that is only called once for that shared constant. It's like this:
public class Foo {
public static let shared = Foo()
private init() { /* ... */ }
public func bar() { /* ... */ }
public func baz() { /* ... */ }
}
// Meanwhile, in multiple places upon multiple threads:
Foo.shared.bar()
Foo.shared.baz()
If I have a dozen threads calling functions on that constant, does it pause all calls until that initializer completes, or should I have some protections within those instance functions to wait for initialization to complete?
init
that's documented to be thread-safe, it's the assignment to that static property.bar
andbaz
are. E.g., if those two methods perform some unsynchronized access to some shared resource, then they won’t be. It depends entirely upon what these two methods do. But they don’t magically become threadsafe because they’re methods of this singleton.