Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety in Swift

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.

like image 218
AJ_1310 Avatar asked Aug 04 '14 13:08

AJ_1310


People also ask

What is thread-safety in Swift?

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.

How do you make a thread-safe in Swift?

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.

Are Swift properties thread-safe?

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.

Is Lazy thread-safe Swift?

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.


1 Answers

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:

  • https://stackoverflow.com/a/28976644/2317256
like image 90
skim Avatar answered Sep 23 '22 23:09

skim