1

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?

13
  • 1
    It is documented to be thread safe. See for example stackoverflow.com/a/24147830/1187415.
    – Martin R
    Commented Jan 14, 2019 at 21:58
  • 2
    To be clear here, it's not init that's documented to be thread-safe, it's the assignment to that static property.
    – jscs
    Commented Jan 14, 2019 at 22:04
  • 2
    Since Swift won't let you call a function until the object is initialised, and the assignment to the static and its associated initialisation is guaranteed to occur only once and is thread safe, you know that the function invocations will also be safe.
    – Paulw11
    Commented Jan 14, 2019 at 22:09
  • 4
    Instantiation and access to the singleton, itself, is threadsafe, but that doesn’t mean that bar and baz 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.
    – Rob
    Commented Jan 14, 2019 at 22:12
  • 1
    @Rob great point! They can be called simultaneously (to each-other or themselves); they don't do anything thread-dangerous. They simply rely on the initializer completing before they run, so they can't run simultaneously to the initializer.
    – Ky -
    Commented Jan 14, 2019 at 22:14

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.