Home IOS Development The fundamentals of structured concurrency in Swift defined – Donny Wals

The fundamentals of structured concurrency in Swift defined – Donny Wals

The fundamentals of structured concurrency in Swift defined – Donny Wals


Printed on: March 17, 2023

Swift Concurrency closely depends on an idea referred to as Structured Concurrency to explain the connection between mum or dad and youngster duties. It finds its foundation within the fork be a part of mannequin which is a mannequin that stems from the sixties.

On this put up, I’ll clarify what structured concurrency means, and the way it performs an necessary function in Swift Concurrency.

Observe that this put up shouldn’t be an introduction to utilizing the async and await key phrases in Swift. I’ve numerous posts on the subject of Swift Concurrency that you could find proper right here. These posts all assist you to be taught particular bits and items of recent Concurrency in Swift. For instance, how you should utilize activity teams, actors, async sequences, and extra.

If you happen to’re searching for a full introduction to Swift Concurrency, I like to recommend you try my guide. In my guide I am going in depth on all of the necessary components of Swift Concurrency that it’s worthwhile to know in an effort to take advantage of out of recent concurrency options in Swift.

Anyway, again to structured concurrency. We’ll begin by trying on the idea from a excessive stage earlier than a number of examples of Swift code that illustrates the ideas of structured concurrency properly.

Understanding the idea of structured concurrency

The ideas behind Swift’s structured concurrency are neither new nor distinctive. Positive, Swift implements some issues in its personal distinctive manner however the core thought of structured concurrency could be dated again all the way in which to the sixties within the type of the fork be a part of mannequin.

The fork be a part of mannequin describes how a program that performs a number of items of labor in parallel (fork) will await all work to finish, receiving the outcomes from each bit of labor (be a part of) earlier than persevering with to the subsequent piece of labor.

We are able to visualize the fork be a part of mannequin as follows:

Fork Join Model example

Within the graphic above you possibly can see that the primary activity kicks off three different duties. One among these duties kicks off some sub-tasks of its personal. The unique activity can’t full till it has acquired the outcomes from every of the duties it spawned. The identical applies to the sub-task that kicks of its personal sub-tasks.

You’ll be able to see that the 2 purple coloured duties should full earlier than the duty labelled as Job 2 can full. As soon as Job 2 is accomplished we are able to proceed with permitting Job 1 to finish.

Swift Concurrency is closely based mostly on this mannequin nevertheless it expands on a number of the particulars a bit bit.

For instance, the fork be a part of mannequin doesn’t formally describe a manner for a program to make sure right execution at runtime whereas Swift does present these sorts of runtime checks. Swift additionally gives an in depth description of how error propagation works in a structured concurrency setting.

When any of the kid duties spawned in structured concurrency fails with an error, the mum or dad activity can determine to deal with that error and permit different youngster duties to renew and full. Alternatively, a mum or dad activity can determine to cancel all youngster duties and make the error the joined results of all youngster duties.

In both situation, the mum or dad activity can’t full whereas the kid duties are nonetheless working. If there’s one factor it’s best to perceive about structured concurrency that might be it. Structured concurrency’s fundamental focus is describing how mum or dad and youngster duties relate to one another, and the way a mum or dad activity cannot full when a number of of its youngster duties are nonetheless working.

So what does that translate to after we discover structured concurrency in Swift particularly? Let’s discover out!

Structured concurrency in motion

In its easiest and most simple kind structured concurrency in Swift signifies that you begin a activity, carry out some work, await some async calls, and ultimately your activity completes. This might look as follows:

func parseFiles() async throws -> [ParsedFile] {
  var parsedFiles = [ParsedFile]()

  for file in listing {
    let consequence = strive await parseFile(file)

  return parsedFiles

The execution for our perform above is linear. We iterate over a listing of information, we await an asynchronous perform for every file within the listing, and we return an inventory of parsed information. We solely work on a single file at a time and at no level does this perform fork out into any parallel work.

We all know that in some unspecified time in the future our parseFiles() perform was referred to as as a part of a Job. This activity could possibly be a part of a bunch of kid duties, it could possibly be activity that was created with SwiftUI’s activity view modifier, it could possibly be a activity that was created with Job.indifferent. We actually don’t know. And it additionally doesn’t actually matter as a result of whatever the activity that this perform was referred to as from, this perform will all the time run the identical.

Nevertheless, we’re not seeing the facility of structured concurrency on this instance. The actual energy of structured concurrency comes after we introduce youngster duties into the combo. Two methods to create youngster duties in Swift Concurrency are to leverage async let or TaskGroup. I’ve detailed posts on each of those subjects so I gained’t go in depth on them on this put up:

Since async let has essentially the most light-weight syntax of the 2, I’ll illustrate structured concurrency utilizing async let reasonably than via a TaskGroup. Observe that each methods spawn youngster duties which signifies that they each adhere to the principles from structured concurrency though there are variations within the issues that TaskGroup and async let remedy.

Think about that we’d prefer to implement some code that follows the fork be a part of mannequin graphic that I confirmed you earlier:

Fork Join Model example

We might write a perform that spawns three youngster duties, after which one of many three youngster duties spawns two youngster duties of its personal.

The next code exhibits what that appears like with async let. Observe that I’ve omitted varied particulars just like the implementation of sure lessons or features. The main points of those are usually not related for this instance. The important thing info you’re searching for is how we are able to kick off numerous work whereas Swift makes certain that each one work we kick off is accomplished earlier than we return from our buildDataStructure perform.

func buildDataStructure() async -> DataStructure {
  async let configurationsTask = loadConfigurations()
  async let restoredStateTask = loadState()
  async let userDataTask = fetchUserData()

  let config = await configurationsTask
  let state = await restoredStateTask
  let information = await userDataTask

  return DataStructure(config, state, information)

func loadConfigurations() async -> [Configuration] {
  async let localConfigTask = configProvider.native()
  async let remoteConfigTask = configProvider.distant()

  let (localConfig, remoteConfig) = await (localConfigTask, remoteConfigTask)

  return localConfig.apply(remoteConfig)

The code above implements the identical construction that’s outlined within the fork be a part of pattern picture.

We do every thing precisely as we’re presupposed to. All duties we create with async let are awaited earlier than the perform that we created them in returns. However what occurs after we neglect to await certainly one of these duties?

For instance, what if we write the next code?

func buildDataStructure() async -> DataStructure? {
  async let configurationsTask = loadConfigurations()
  async let restoredStateTask = loadState()
  async let userDataTask = fetchUserData()

  return nil

The code above will compile completely effective. You’d see a warning about some unused properties however all in all of your code will compile and it’ll run simply effective.

The three async let properties which can be created every symbolize a baby activity and as you understand every youngster activity should full earlier than their mum or dad activity can full. On this case, that assure shall be made by the buildDataStructure perform. As quickly as that perform returns it should cancel any working youngster duties. Every youngster activity should then wrap up what they’re doing and honor this request for cancellation. Swift won’t ever abruptly cease executing a activity attributable to cancellation; cancellation is all the time cooperative in Swift.

As a result of cancellation is cooperative Swift won’t solely cancel the working youngster duties, it should additionally implicitly await them. In different phrases, as a result of we don’t know whether or not cancellation shall be honored instantly, the mum or dad activity will implicitly await the kid duties to ensure that all youngster duties are accomplished earlier than resuming.

How unstructured and indifferent duties relate to structured concurrency

Along with structured concurrency, now we have unstructured concurrency. Unstructured concurrency permits us to create duties which can be created as stand alone islands of concurrency. They don’t have a mum or dad activity, they usually can outlive the duty that they have been created from. Therefore the time period unstructured. While you create an unstructured activity, sure attributes from the supply activity are carried over. For instance, in case your supply activity is fundamental actor sure then any unstructured duties created from that activity will even be fundamental actor sure.

Equally should you create an unstructured activity from a activity that has activity native values, these values are inherited by your unstructured activity. The identical is true for activity priorities.

Nevertheless, as a result of an unstructured activity can outlive the duty that it acquired created from, an unstructured activity won’t be cancelled or accomplished when the supply activity is cancelled or accomplished.

An unstructured activity is created utilizing the default Job initializer:

func spawnUnstructured() async {
  Job {
    print("that is printed from an unstructured activity")

We are able to additionally create indifferent duties. These duties are each unstructured in addition to utterly indifferent from the context that they have been created from. They don’t inherit any activity native values, they don’t inherit actor, and they don’t inherit precedence.

I cowl indifferent and unstructured duties extra in depth proper right here.

In Abstract

On this put up, you realized what structured concurrency means in Swift, and what its main rule is. You noticed that structured concurrency is predicated on a mannequin referred to as the fork be a part of mannequin which describes how duties can spawn different duties that run in parallel and the way all spawned duties should full earlier than the mum or dad activity can full.

This mannequin is actually highly effective and it gives lots of readability and security round the way in which Swift Concurrency offers with mum or dad / youngster duties which can be created with both a activity group or an async let.

We explored structured concurrency in motion by writing a perform that leveraged varied async let properties to spawn youngster duties, and also you realized that Swift Concurrency gives runtime ensures round structured concurrency by implicitly awaiting any working youngster duties earlier than our mum or dad activity can full. In our instance this meant awaiting all async let properties earlier than getting back from our perform.

You additionally realized that we are able to create unstructured or indifferent duties with Job.init and Job.indifferent. I defined that each unstructured and indifferent duties are by no means youngster duties of the context that they have been created in, however that unstructured duties do inherit some context from the context they have been created in.

All in all a very powerful factor to grasp about structured concurrency is that it present clear and inflexible guidelines across the relationship between mum or dad and youngster duties. Specifically it describes how all youngster duties should full earlier than a mum or dad activity can full.



Please enter your comment!
Please enter your name here