Skip to content
Tutorials Center
My learning

Topics

Lesson 89 of 146 ยท Concurrency

Synchronization and Shared State

Learn the Swift Synchronization module - Mutex, withLock, Atomic, compareExchange, memory ordering, and when to choose locks or atomics over actors, with real Swift 6 compiler errors.

Sooner or later two pieces of code need to touch the same data. A cache that several tasks fill, a counter that tracks how many requests are running, a flag that tells a worker to stop. If both sides can write at the same moment you have a data race, and Swift 6 treats data races as compile-time errors where it can see them. This lesson is about the tools you use to share state correctly.

You already know one answer, the actor: an actor owns its state and processes one request at a time. Actors are the default choice, but they have a cost. Every call from the outside is asynchronous (await), and an actor can interleave work at each await. For small, fast, synchronous critical sections there are two lower-level tools in the standard library's Synchronization module: Mutex and Atomic. After reading this lesson you will know how each one works, how Swift stops you misusing them, and how to choose between them and actors. It builds on Threads and Dispatch and Sendable and Data Races.

Mutex: one thread at a time, enforced by the type

A mutex (short for mutual exclusion) lets only one thread run a protected piece of code at a time. In older code you wrote a lock next to the data it guarded and had to remember to take it every time. The Swift Mutex<Value> flips this: the protected value lives inside the mutex and is reachable only through withLock. There is simply no way to read it without holding the lock.

Swift Mutex protecting a bank balance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is true, false, 70. Look at what withLock does:

  1. It locks the mutex, waiting if another thread holds it.
  2. It hands your closure the protected value as an inout parameter, so current -= amount changes the real value.
  3. It unlocks when the closure returns, even if the closure throws, and returns whatever the closure returned.

The check (current >= amount) and the update (current -= amount) happen inside one critical section. That matters: if you read the balance in one withLock and subtract in another, another thread could withdraw in between and you would overdraw the account. Keep a whole "check then act" decision in a single withLock.

Notice also that Account is declared Sendable with no @unchecked. That is allowed because its only stored property is a let holding a Mutex, and Mutex is itself Sendable. The compiler can prove the class is safe, which is a real improvement over NSLock plus @unchecked Sendable.

Sharing a Mutex across tasks

Because the class is Sendable, you can hand one instance to many tasks. Here a hundred child tasks each add to a shared total.

Swift Many tasks, one Mutex

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Each word is recorded 30 times, so the program prints ["blue=30", "green=30", "red=30"] on every run. The report sorts the dictionary inside the lock before returning, because dictionary order is random in Swift and would otherwise change from run to run.

What Mutex will not let you do

Mutex is a noncopyable type (see Noncopyable Types): if you could copy it, you would end up with two locks guarding one value, which defeats the purpose. The compiler enforces that.

Swift Copying a Mutex (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler answers:

TEXT
main.swift:4:14: error: 'first' is borrowed and cannot be consumed

To share a mutex, store it in a class (or capture the class), never copy it.

A second rule is just as important: a mutex is not re-entrant. If code that already holds the lock tries to take it again, it would wait for itself forever. Swift catches the mistake and stops the program.

Swift Locking twice from the same thread (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The run ends in a crash (signal SIGILL) with this line on standard error:

TEXT
Synchronization/LinuxImpl.swift:157: Fatal error: Recursive call to lock Mutex

The usual cause is a method that holds the lock and calls another method that also takes it. Structure your code so that public methods take the lock exactly once, and private helpers that assume the lock is held receive the protected value as a parameter.

Two more habits keep mutexes healthy:

  • Keep the closure short. Do the slow work (network calls, file reads, sorting a huge array) outside the lock, and only update the shared value inside. Other threads wait while you hold it.
  • Never await inside withLock. The closure is synchronous, so the compiler will not even let you suspend there. That is deliberate: a lock held across a suspension point is a classic deadlock.

Mutex also offers withLockIfAvailable, which returns nil immediately instead of waiting when somebody else holds the lock. It is useful for "try to refresh the cache, but skip if another task is already doing it".

Atomic: lock-free single values

Sometimes the shared state is one number or one flag. For that, even a mutex is more than you need. An atomic value is a variable that the CPU can read and update in a single indivisible step. No lock is taken, so nobody waits.

Atomic<Value> supports integers, Bool, and a few other simple types. Typical operations are load, store, add, subtract, exchange and compareExchange. Every operation takes an ordering: argument that says how much the CPU may reorder surrounding memory operations. If you are unsure, use .sequentiallyConsistent, the strictest and always correct choice. .relaxed is correct for a plain counter where you only care about the final total.

Swift An atomic counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The total is always hits: 4000. Notice that the global constant hits is captured by a @Sendable closure without any complaint, because Atomic is Sendable.

Like Mutex, Atomic is noncopyable, and it has one extra rule: it must be a let. A var would let you replace it wholesale, which is not an atomic operation.

Swift Declaring an Atomic with var (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

TEXT
main.swift:3:5: error: variable of type 'Atomic<Int>' must be declared with a 'let'

compareExchange: the building block of lock-free code

compareExchange(expected:desired:ordering:) says: "if the current value equals expected, replace it with desired; either way tell me what happened". It returns a tuple (exchanged: Bool, original: Value). Only one caller can win when several race, which makes it perfect for "do this exactly once" logic.

Swift Run-once with compareExchange

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first call wins and prints starting the service. The second finds true and prints already started (original value was true). After exchange resets the flag (and returns the old value, true), the next call wins again.

Atomics are powerful and unforgiving. They protect one value. If two values must change together, such as a balance and a transaction count, atomics cannot do it, because another thread could look between the two updates. For multi-field invariants use a Mutex (put both fields in one struct inside it) or an actor.

Actors versus locks

Now you have three tools for the same problem. A quick comparison using the same task: a counter incremented from a hundred tasks.

Swift The same counter as an actor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

It prints 100. Compare it with the Mutex version: the actor needs await at every call and every caller must be asynchronous, but you never write a lock at all. The compiler guarantees that the state is only touched on the actor.

Actor Mutex Atomic
Call style await (asynchronous) plain synchronous call plain synchronous call
Protects any state, many fields any state, many fields one simple value
Can suspend inside yes (and then interleave) no, never not applicable
Waiting task suspends, thread is free thread blocks no waiting
Best for app-level state, long operations tiny critical sections, synchronous APIs counters, flags, run-once

Rules of thumb:

  • Start with an actor (or @MainActor for UI-facing state). It is the clearest design and the compiler checks it.
  • Choose Mutex when the API must stay synchronous (a Sendable cache used from non-async code, a property getter, a protocol requirement) and the critical section is a few lines long.
  • Choose Atomic for a counter, a "should stop" flag, a generation number or a run-once guard.
  • Avoid both for long operations. An actor method that awaits network calls lets other callers in at each await, so re-check your assumptions after every suspension; a mutex held across slow work blocks every other thread.

Platform locks you will see in other code

Apple platforms also have OSAllocatedUnfairLock (in the os module), which works like Mutex and predates it. It is not available on Linux, so the following is a read-only example and cannot run on this site:

Swift
// Read-only example: Apple platforms only (import os)
import os

final class Cache: Sendable {
    private let storage = OSAllocatedUnfairLock(initialState: [String: Int]())

    func value(for key: String) -> Int? {
        storage.withLock { $0[key] }
    }
}

Mutex requires newer operating systems on Apple platforms (iOS 18, macOS 15 and later), so code that supports older versions still uses OSAllocatedUnfairLock or NSLock. On Linux and for new code you target, Mutex is the one to learn.

The escape hatch

When you cannot restructure legacy code, Swift 6 gives you two ways to say "I take responsibility": @unchecked Sendable on a type, and nonisolated(unsafe) on a variable. Both silence the checker and bring the data-race risk back. Use them only around code that is protected by some other mechanism you can name, and leave a comment saying which one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main advantage of Mutex<Value> over an NSLock stored next to a variable?

    The value lives inside the mutex. The only way to reach it is withLock, which also unlocks for you. Mutex is noncopyable and its closure is synchronous.
  2. 2. What happens if code inside counter.withLock { } calls counter.withLock { } again?

    A Mutex is not re-entrant. Taking it twice from the same thread would wait forever, so the runtime reports a fatal error instead.
  3. 3. Which tool is the right fit for a boolean 'should stop' flag read by many threads?

    A single simple value is exactly what Atomic is for. It must be a let, and no lock is needed. A mutex or actor would also work but costs more.
  4. 4. Why can a balance and a transaction count not be kept consistent with two separate atomics?

    Each atomic operation is indivisible by itself, but two operations in a row are not. Multi-field invariants need a Mutex around a struct holding both fields, or an actor.
  5. 5. Which is the best first choice for application-level shared state that is accessed from async code?

    Actors give compiler-checked isolation and a clear design. Reach for Mutex when the API must stay synchronous and the critical section is tiny.

Summary

  • Mutex<Value> (module Synchronization) stores the value inside the lock; you reach it only through withLock, which unlocks automatically and returns the closure's result.
  • A class whose only stored properties are let constants of Sendable types, such as a Mutex, can be Sendable without @unchecked.
  • Keep a whole check-then-act decision inside one withLock; keep the closure short; never lock twice (a Mutex is not re-entrant: "Recursive call to lock Mutex").
  • Mutex and Atomic are noncopyable; Atomic must be declared with let.
  • Atomic handles one simple value without locking: add, load, store, exchange, compareExchange. Use .sequentiallyConsistent unless you know why a weaker ordering is correct.
  • Actors need await but no explicit locking and suit app-level state; Mutex suits small synchronous critical sections; Atomic suits counters, flags and run-once logic.
  • OSAllocatedUnfairLock is Apple-only; @unchecked Sendable and nonisolated(unsafe) are last-resort escape hatches.

Next: Text Processing moves on to the standard library and Foundation, starting with splitting, trimming and searching strings.