🎉 Black Friday Sale! Save 30% when you subscribe today.

Concurrency's Future: Sendable and Actors

Episode #193 • Jun 20, 2022 • Subscriber-Only

When working with concurrent code, you must contend with data synchronization and data races. While the tools of the past made it difficult to reason about these issues, Swift’s new tools make it a breeze, including the Sendable protocol, @Sendable closures, and actors.

Previous episode
Concurrency's Future: Sendable and Actors
Next episode
Locked

Unlock This Episode

Our Free plan includes 1 subscriber-only episode of your choice, plus weekly updates from our newsletter.

Sign in with GitHub

Introduction

So we have now seen that the concepts of asynchrony are deeply baked into the Swift language. If you want to perform asynchronous work you need to be in an asynchronous context, which is something that the compiler explicitly knows about. You either need to implement your function with the async keyword applied to it, which means the caller is responsible for providing the asynchronous context, or you need to spin up a new task using the Task initializer. The choice between these two styles of providing an asynchronous context are very different, but we will dive into that topic in a moment.

Before that, there was another topic we delved into for both threads and dispatch queues, and that is data synchronization and data races. We saw that if we accessed mutable state from multiple threads or queues, then we leave ourselves open to data races, where two threads simultaneously read and write to the same value. When this happens we get unexpected results, such as incrementing a counter 1,000 times from 1,000 different threads causes the count to be slightly less than 1,000. This happens when one thread writes the count in between the moment when another thread reads the count and then writes to it. In that case the second write will mutate with an out-of-date value.

Let’s see what new tools Swift gives us to solve this problem.

Sendable and @Sendable


References

Downloads

Get started with our free plan

Our free plan includes 1 subscriber-only episode of your choice, access to 64 free episodes with transcripts and code samples, and weekly updates from our newsletter.

View plans and pricing