Rule of thumb:
- Never access (read or write) a
var
from more than one thread (or queue). Only yourtestScenarioC4()
adheres to this. - If using value types, you can safely use
let
s 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 - If using reference types, it's only safe if all their properties are
let
s recursively (value type properties can of course bevar
). 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.