Understanding Swift's value type thread safety

Rule of thumb:

  1. Never access (read or write) a var from more than one thread (or queue). Only your testScenarioC4() adheres to this.
  2. If using value types, you can safely use lets from more than one thread/queue. You can also make new copies, even if they use copy-on-write internally (e.g. the collection types). If a value type has any reference type properties, see 3 below :slight_smile:
  3. If using reference types, it's only safe if all their properties are lets recursively (value type properties can of course be var). Or are otherwise made thread-safe.

For thread-safety often a serial dispatch queue or the unfair lock will be your best options. If speed matters a lot, then the unfair lock is probably what you want. If you have different priorities / QoS inside your program, you should be wary of using the concurrent queue with a barrier suggestion above to implement a R/W lock, as that doesn't support priority inversion avoidance.

5 Likes