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.