[swift-dev] What about concurrency?
antonvmironov at gmail.com
Sun Sep 4 17:00:45 CDT 2016
My job is mostly consists of writing core functionality for macOS (and I love core functionality). My code must take advantage of concurrency. I've been looking for solutions that allow me to write clean and (most important) reliable concurrent code. I would love to discuss some of those solutions and find out if they are any close to what Swift team want to implement in Swift 4+.
1. using actors
Actor (in this context) is a stateful object that owns private serial queue and performs all changes of internal state on that queue. In my opinion, it fits into actor model https://en.wikipedia.org/wiki/Actor_model (where a mailbox is an internal queue). So 95% of classes I make are folding into two categories: concurrency-aware actors and other objects that are made for single threaded usage.
There is a very common corner case of NSResponder/UIResponder (view controllers, windows, views, quartz core layers and etc) but they are basically components of some imaginary global actor that live on the main queue.
I also want to thank Apple team for adding dispatchPrecondition(...) function that helps me to detect if I accidently called agent`s private method on the wrong queue.
2. using futures (and streams) instead of callbacks
It saved me from callback hell and helped me to avoid some common issues (such as forgetting to call the callback in some error-handling related cases). The most convincing thing to me was a way of combining multiple futures together. It is far simpler and safer than using group or barrier.
I've used FutureKit for utility app that has a lot of concurrency and it served me very well. Now I am trying to implement something like it for Swift 3 with more strict error handling and with streams.
3. no atomic properties and locks (except for locks in FutureKit)
I've learned the hard way that locks are making a lot of troubles. So now I am free from them and I am very glad about it.
I also want to thank Swift team for not adding @synchronized to Swift because this decision is really cleaned my mind.
So what do you think?
More information about the swift-dev