I'm working on a project to handle state machine changes that need to be obeyed between numerous thread but just stumbled onto they are nonatomic by default. Is there a way to make Swift properties thread-safe or atomic at the time of Xcode6-Beta4? Thanks in advance.
Immutable arrays (declared using let) are thread-safe since it is read-only. But mutable arrays are not thread-safe. Many threads can read a mutable instance of an array simultaneously without an issue but it is unsafe to let one thread modify the array while another is reading it.
Swift provides no thread-safety whatsoever (it does not have any concept of threads). You're responsible for synchronizing accesses to objects, including standard library types yourself, especially with standard library types.
Unfortunately most of the Swift data types are not thread safe by default, so if you want to achieve thread-safety you usually had to work with serial queues or locks to guarantee the mutual exclusivity of a given variable.
Another problem is that lazy var is not thread-safe which means the closure can get executed multiple times due to accesses from different threads.
I think Alexander W has the right idea, but I would advise synchronizing on self
as a general rule. Perhaps the suggestion I posted here may help:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With