Search code examples
swiftconcurrencystatic

In Swift, why is initialization of lazy static variables thread-safe? How is it implemented?


How does swift implement thread safety of lazy static variable allocation/evaluation? Is there some global lock for all static variable access that all calls go through?


Solution

  • Global variables are initialised using swift_once.

    swift_once

    @convention(thin) (Builtin.RawPointer, @convention(thin) () -> ()) -> ()
    

    Used to lazily initialize global variables. The first parameter must point to a word-sized memory location that was initialized to zero at process start. It is undefined behavior to reference memory that has been initialized to something other than zero or written to by anything other than swift_once in the current process's lifetime. The function referenced by the second parameter will have been run exactly once in the time between process start and the function returns.

    On Darwin platforms, this is basically a wrapper around dispatch_once_f. As far as I know, dispatch_once_f doesn't use a "global lock". The initialisation of two global variables can happen simultaneously.