Friday, August 18, 2017

Concurrency in Swift: One Possible Approach

Chris Lattner (tweet):

We focus on task-based concurrency abstractions commonly encountered in client and server applications, particularly those that are highly event driven (e.g. responding to UI events or requests from clients). This does not attempt to be a comprehensive survey of all possible options, nor does it attempt to solve all possible problems in the space of concurrency. Instead, it outlines a single coherent design thread that can be built over the span of years to incrementally drive Swift to further greatness.


Modern Cocoa development involves a lot of asynchronous programming using closures and completion handlers, but these APIs are hard to use. This gets particularly problematic when many asynchronous operations are used, error handling is required, or control flow between asynchronous calls is non-trivial. […] Error handling is particularly ugly, because Swift’s natural error handling mechanism cannot be used.


Asynchrony is the next fundamental abstraction that must be tackled in Swift, because it is essential to programming in the real world where we are talking to other machines, to slow devices (spinning disks are still a thing!), and looking to achieve concurrency between multiple independent operations. Fortunately, Swift is not the first language to face these challenges: the industry as a whole has fought this dragon and settled on async/await as the right abstraction. We propose adopting this proven concept outright (with a Swift spin on the syntax). Adopting async/await will dramatically improve existing Swift code, dovetailing with existing and future approaches to concurrency.

The next step is to define a programmer abstraction to define and model the independent tasks in a program, as well as the data that is owned by those tasks. We propose the introduction of a first-class actor model, which provides a way to define and reason about independent tasks who communicate between themselves with asynchronous message sending. The actor model has a deep history of strong academic work and was adopted and proven in Erlang and Akka, which successfully power a large number of highly scalable and reliable systems. With the actor model as a baseline, we believe we can achieve data isolation by ensuring that messages sent to actors do not lead to shared mutable state.

Previously: Swift: Challenges and Opportunity for Language and Compiler Research, Python 3.5: async and await, C# 5.0’s async.

Update (2017-09-11): See also: Swift Unwrapped.

1 Comment RSS · Twitter

[…] Concurrency in Swift: One Possible Approach […]

Leave a Comment