Mutex and Atomic with the Synchronization module
suggest changeSwift 6.0 added the Synchronization module to the standard library. It has two low-level tools for sharing mutable state between threads:
Mutex<Value>is a lock that owns the value it protects. You can only reach the value insidewithLock { }.Atomic<Value>is a single integer,Bool, pointer or small enum that many threads can read and update without a lock.
Both are synchronous. You call them without await, from any function. That is the main difference from an actor.
The module ships with the Swift 6 toolchain on Linux and Windows. On Apple platforms it needs macOS 15, iOS 18, watchOS 11, tvOS 18 or visionOS 2. To support older OS versions you have to check with if #available or mark your code with @available.
The examples were compiled with Swift 6.4 on Windows, in the Swift 6 language mode:
swiftc -swift-version 6 -parse-as-library main.swift
Mutex: a lock that owns its data
The Actors article starts with a class counter that loses increments when many tasks update it. Here is the same counter protected by a Mutex:
import Synchronization
final class Counter: Sendable {
private let value = Mutex(0)
func increment() {
value.withLock { $0 += 1 }
}
var current: Int {
value.withLock { $0 }
}
}
@main
struct App {
static func main() async {
let counter = Counter()
await withTaskGroup(of: Void.self) { group in
for _ in 0..<100_000 {
group.addTask { counter.increment() } // no await
}
}
print(counter.current)
}
}
Output:
100000
How it works:
Mutex(0)creates a lock and stores the protected value, anInt, inside it.withLocktakes the lock, gives the closureinoutaccess to the value, and releases the lock when the closure returns or throws. Only one thread at a time runs inside the closure. Other threads block until the lock is free.- The value can't be reached any other way, so you can't forget to take the lock.
Counteris declaredSendablewithout@unchecked. A class can beSendableonly if all its stored properties are immutable andSendable.valueis alet, andMutexisSendable, so the compiler accepts it.
Compare this with the same counter written as an actor. There every caller has to await counter.increment(). Here increment() is an ordinary synchronous method.
Using a Mutex from threads, not tasks
Because withLock is synchronous, a Mutex works with any kind of thread. That includes Grand Central Dispatch, Thread, and callbacks coming from C libraries. A global let is allowed in Swift 6, because Mutex is Sendable:
import Foundation
import Synchronization
let counter = Mutex(0) // a global `let` is fine: Mutex is Sendable
func work(iterations: Int) {
for _ in 0..<iterations {
counter.withLock { $0 += 1 }
}
}
@main
struct App {
static func main() {
// 8 threads from the GCD pool, all calling a synchronous function
DispatchQueue.concurrentPerform(iterations: 8) { _ in
work(iterations: 10_000)
}
print(counter.withLock { $0 })
}
}
Output:
80000
DispatchQueue.concurrentPerform is covered in Concurrent Loops.
Returning values, throwing, and withLockIfAvailable
Whatever the closure returns, withLock returns. That lets you read a value, or check and update the state in one step. If the closure throws, the lock is released and the error is rethrown. withLock supports typed throws:
import Synchronization
enum StockError: Error {
case notEnough(item: String, available: Int)
}
final class Inventory: Sendable {
private let stock = Mutex<[String: Int]>(["apple": 5, "pear": 2])
// the closure's return value becomes withLock's return value
func count(of item: String) -> Int {
stock.withLock { $0[item, default: 0] }
}
// check and update in one critical section
func take(_ amount: Int, of item: String) throws(StockError) -> Int {
try stock.withLock { (stock) throws(StockError) -> Int in
let available = stock[item, default: 0]
guard available >= amount else {
throw .notEnough(item: item, available: available)
}
stock[item] = available - amount
return available - amount
}
}
// gives up instead of waiting if another thread holds the lock
func tryReport() -> String? {
stock.withLockIfAvailable { stock in
stock.sorted { $0.key < $1.key }
.map { "\($0.key)=\($0.value)" }
.joined(separator: " ")
}
}
}
@main
struct App {
static func main() {
let inventory = Inventory()
do {
print("left:", try inventory.take(3, of: "apple"))
print("left:", try inventory.take(3, of: "apple"))
} catch {
print("error:", error)
}
print("apples:", inventory.count(of: "apple"))
print("report:", inventory.tryReport() ?? "busy")
}
}
Output:
left: 2
error: notEnough(item: "apple", available: 2)
apples: 2
report: apple=2 pear=2
Notes:
- The check (
available >= amount) and the update run under one lock. Two threads can't both pass the check against the same stock. If you took the lock twice, once to read and once to write, another thread could change the stock in between. - The closure in
takedeclaresthrows(StockError). Without that annotation, the compiler treats the closure as throwingany Error. You then geterror: thrown expression type 'any Error' cannot be converted to error type 'StockError'. withLockIfAvailablereturnsnilinstead of blocking when another thread holds the lock. Otherwise it runs the closure and returns the closure's result as an optional.
Mutex compared with NSLock
Before Swift 6 you usually paired a lock with a separate variable:
import Foundation
final class OldCache: @unchecked Sendable {
private let lock = NSLock()
private var storage: [String: Int] = [:]
func set(_ key: String, _ value: Int) {
lock.lock()
defer { lock.unlock() }
storage[key] = value
}
func get(_ key: String) -> Int? {
storage[key] // oops: forgot to take the lock
}
}
This compiles and seems to work, but get has a data race. The compiler can't help you:
- Without
@unchecked, the class doesn't compile:error: stored property 'storage' of 'Sendable'-conforming class 'OldCache' is mutable. - With
@unchecked Sendable, you are telling the compiler "trust me", and it stops checking (see Sendable and Swift 6 data-race safety).
Mutex combines the lock and the data, so both problems go away. The class can be plain Sendable, and there is no way to read storage without the lock:
import Synchronization
final class Cache: Sendable {
private let storage = Mutex<[String: Int]>([:])
func set(_ key: String, _ value: Int) {
storage.withLock { $0[key] = value }
}
func get(_ key: String) -> Int? {
storage.withLock { $0[key] }
}
}
The same goes for the old pattern of a serial DispatchQueue used as a lock with queue.sync { } (see Running tasks in a Grand Central Dispatch GCD queue). A Mutex is simpler, and the compiler checks it.
Why Mutex and Atomic are ~Copyable
Mutex and Atomic are structs, but they are declared ~Copyable (noncopyable). A copy of a lock would be a second, independent lock with its own copy of the value. Two threads using the two copies would not exclude each other at all. So Swift forbids the copy.
That has a few consequences. Assigning a mutex to another constant moves it, and the old name can't be used anymore:
import Synchronization
func copies() {
let a = Mutex(0)
let b = a
a.withLock { $0 += 1 }
b.withLock { $0 += 1 }
}
error: 'a' used after consume
note: consumed here
note: used here
A regular, copyable struct can't contain one:
struct Stats {
let hits = Mutex(0)
}
error: stored property 'hits' of 'Copyable'-conforming struct 'Stats' has non-Copyable type 'Mutex<Int>'
note: consider adding '~Copyable' to struct 'Stats'
To share a mutex, you usually do one of these things:
- Store it as a
letproperty of afinal class, as in the examples above. Every reference to the object shares the same mutex. - Use a global or
static let. - Make the containing struct
~Copyabletoo:
import Synchronization
struct Stats: ~Copyable {
let hits = Mutex(0)
let misses = Mutex(0)
func record(hit: Bool) {
if hit {
hits.withLock { $0 += 1 }
} else {
misses.withLock { $0 += 1 }
}
}
}
let stats = Stats()
@main
struct App {
static func main() async {
await withTaskGroup(of: Void.self) { group in
for i in 0..<1_000 {
group.addTask { stats.record(hit: i % 4 != 0) }
}
}
print("hits:", stats.hits.withLock { $0 }, "misses:", stats.misses.withLock { $0 })
}
}
Output:
hits: 750 misses: 250
withLock is a borrowing method, so a let mutex is enough. You never need var. For Atomic, a var is an error: error: variable of type 'Atomic<Int>' must be declared with a 'let'.
Rules for using a Mutex
No await inside the lock. The closure passed to withLock is synchronous, so you can't suspend while holding the lock:
func download() async -> Int { 42 }
func refresh(_ m: borrowing Mutex<Int>) async {
m.withLock { $0 = await download() }
}
error: cannot pass function of type '(inout sending Int) async -> sending ()' to parameter expecting synchronous function type
note: 'async' inferred from asynchronous operation used here
Do the async work first, then take the lock to store the result:
func refresh(_ m: borrowing Mutex<Int>) async {
let value = await download()
m.withLock { $0 = value }
}
This rule protects you. A task that is suspended while holding a lock would block every other thread that wants the lock, for as long as the suspension lasts.
Keep critical sections short. While one thread is inside withLock, other threads that want the lock are blocked. A blocked thread can't do other work, unlike a task waiting on an actor, which is suspended. Inside the lock, don't do I/O or slow computation, and don't call code you don't control.
Don't lock the same mutex twice. Mutex is not recursive. The documentation says that calling withLock again from inside the closure "has behavior that is platform dependent". The program may crash or deadlock, but the lock is never acquired a second time. Be careful with a method that holds the lock and calls another method of the same class that takes the lock again.
Don't hold two mutexes in different orders. If thread 1 locks a and then b, while thread 2 locks b and then a, they can deadlock. Prefer one mutex around a struct or tuple of related values over several mutexes.
Mutex or actor?
Both protect shared mutable state. The difference is how callers wait:
- With an actor, callers
await. While a task waits, it is suspended and no thread is blocked. But callers have to beasync. - With a Mutex, callers block for the (short) time the lock is held. Any function can call it, including synchronous protocol requirements, callbacks,
deinit, and code that isn't part of Swift concurrency.
A common case is a synchronous protocol requirement that needs mutable state. In the Actors article, a nonisolated var description can only use let properties. With a Mutex it can read anything:
import Synchronization
final class Session: Sendable, CustomStringConvertible {
let user: String
private let state = Mutex<(visits: Int, lastPage: String)>((0, "-"))
init(user: String) { self.user = user }
func visit(_ page: String) {
state.withLock {
$0.visits += 1
$0.lastPage = page
}
}
// a synchronous protocol requirement that reads mutable state
var description: String {
let s = state.withLock { $0 }
return "\(user): \(s.visits) visits, last \(s.lastPage)"
}
}
@main
struct App {
static func main() async {
let session = Session(user: "ann")
await withTaskGroup(of: Void.self) { group in
for page in ["/home", "/cart", "/pay"] {
group.addTask { session.visit(page) }
}
}
session.visit("/thanks")
print(session)
}
}
Output:
ann: 4 visits, last /thanks
A rule of thumb:
- If the state is accessed from async code and operations can take a while (for example, they involve awaiting other work), use an actor.
- If the operations are short and synchronous (updating a dictionary, a counter, a small struct) and you want to call them from anywhere without
await, use aMutex.
Atomic: lock-free single values
Atomic<Value> holds one value that threads update with atomic operations, without a lock. It works with:
- all integer types, including
Int128andUInt128, Bool,- unsafe pointers,
Unmanaged,ObjectIdentifierandDuration, Optionalof a pointer type,FloatandDouble(load, store, exchange and compare-exchange only),WordPair, twoUIntvalues updated together,- your own types that conform to
AtomicRepresentable.
Every operation takes an explicit ordering: argument. There is no default. The next section explains orderings. For counters and statistics, .relaxed is enough:
import Foundation
import Synchronization
let requests = Atomic<Int>(0)
let errors = Atomic<Int>(0)
let peak = Atomic<Int>(0)
let active = Atomic<Int>(0)
func handle(_ id: Int) {
requests.wrappingAdd(1, ordering: .relaxed)
let (_, now) = active.wrappingAdd(1, ordering: .relaxed)
peak.max(now, ordering: .relaxed) // remember the highest value seen
if id % 7 == 0 {
errors.wrappingAdd(1, ordering: .relaxed)
}
active.wrappingSubtract(1, ordering: .relaxed)
}
@main
struct App {
static func main() {
DispatchQueue.concurrentPerform(iterations: 1_000) { id in
handle(id)
}
print("requests:", requests.load(ordering: .relaxed))
print("errors:", errors.load(ordering: .relaxed))
print("active now:", active.load(ordering: .relaxed))
print("peak > 0:", peak.load(ordering: .relaxed) > 0)
let old = requests.exchange(0, ordering: .relaxed) // read and reset
print("reset from", old, "to", requests.load(ordering: .relaxed))
}
}
Output:
requests: 1000
errors: 143
active now: 0
peak > 0: true
reset from 1000 to 0
The basic operations:
| Operation | What it does |
|---|---|
load(ordering:) |
read the value |
store(_:ordering:) |
write a value |
exchange(_:ordering:) |
write a value and return the old one |
compareExchange(expected:desired:ordering:) |
write desired only if the current value equals expected; returns (exchanged, original) |
weakCompareExchange(...) |
like compareExchange, but may fail even when the values are equal; meant for retry loops |
wrappingAdd, wrappingSubtract |
add or subtract, wrapping around on overflow; return (oldValue, newValue) |
add, subtract |
add or subtract, trapping on overflow |
min, max |
store the smaller or larger of the current value and the operand |
bitwiseAnd, bitwiseOr, bitwiseXor |
integer bit operations |
logicalAnd, logicalOr, logicalXor |
the same for Atomic<Bool> |
x += 1 on a normal variable is a read followed by a write, and another thread can write in between. wrappingAdd does the read, the add and the write as one indivisible step. It is called "wrapping" because it overflows silently, like &+:
let a = Atomic<Int8>(127)
print(a.wrappingAdd(1, ordering: .relaxed))
let b = Atomic<Int8>(127)
print(b.add(1, ordering: .relaxed))
Output:
(oldValue: 127, newValue: -128)
*** Program crashed: Illegal instruction at 0x00007ff71a6215a9 ***
add checks for overflow and traps, like +. Its documentation notes that the check usually turns it into a compare-exchange loop. wrappingAdd avoids the loop.
Compare-exchange
compareExchange is the building block for everything else. It means "if the value is still what I think it is, replace it". Otherwise you get back the value that is really there.
An enum with a RawValue that is itself atomic (here UInt8) becomes atomic just by adding the AtomicRepresentable conformance. This service can be started only once, even if many threads call start() at the same time:
import Foundation
import Synchronization
enum State: UInt8, AtomicRepresentable {
case idle, running, stopped
}
final class Service: Sendable {
private let state = Atomic<State>(.idle)
private let starts = Atomic<Int>(0)
// only one caller can move the service from idle to running
func start() -> Bool {
let (exchanged, original) = state.compareExchange(
expected: .idle,
desired: .running,
ordering: .acquiringAndReleasing
)
if exchanged {
starts.wrappingAdd(1, ordering: .relaxed)
} else {
print("start() ignored, state is \(original)")
}
return exchanged
}
func stop() {
state.store(.stopped, ordering: .releasing)
}
var status: String {
"\(state.load(ordering: .acquiring)), started \(starts.load(ordering: .relaxed)) time(s)"
}
}
@main
struct App {
static func main() {
let service = Service()
let winners = Atomic<Int>(0)
DispatchQueue.concurrentPerform(iterations: 4) { _ in
if service.start() {
winners.wrappingAdd(1, ordering: .relaxed)
}
}
print("winners:", winners.load(ordering: .relaxed))
print(service.status)
service.stop()
print("start after stop:", service.start())
print(service.status)
}
}
Output:
start() ignored, state is running
start() ignored, state is running
start() ignored, state is running
winners: 1
running, started 1 time(s)
start() ignored, state is stopped
start after stop: false
stopped, started 1 time(s)
When the new value depends on the old one in a way that no built-in operation covers, use a loop. Read the current value, compute the new one, and try to swap it in. If another thread got there first, retry with the value it left behind. This permit counter never goes below zero:
import Foundation
import Synchronization
// at most `capacity` permits handed out at once
final class Permits: Sendable {
private let available: Atomic<Int>
init(capacity: Int) {
available = Atomic(capacity)
}
func tryAcquire() -> Bool {
var current = available.load(ordering: .relaxed)
while current > 0 {
let (exchanged, original) = available.weakCompareExchange(
expected: current,
desired: current - 1,
ordering: .acquiringAndReleasing
)
if exchanged { return true }
current = original // someone else changed it: retry with the new value
}
return false
}
func release() {
available.wrappingAdd(1, ordering: .releasing)
}
}
@main
struct App {
static func main() {
let permits = Permits(capacity: 3)
let granted = Atomic<Int>(0)
DispatchQueue.concurrentPerform(iterations: 100) { _ in
if permits.tryAcquire() {
granted.wrappingAdd(1, ordering: .relaxed)
}
}
print("granted:", granted.load(ordering: .relaxed))
permits.release()
print("after release:", permits.tryAcquire(), permits.tryAcquire())
}
}
Output:
granted: 3
after release: true false
weakCompareExchange is allowed to fail spuriously, which is fine inside a loop that retries anyway. Outside a loop, use compareExchange.
Memory orderings
An atomic operation is always indivisible. The ordering says what other memory writes become visible together with it. That matters when an atomic value guards ordinary, non-atomic data.
| Ordering | Allowed on | Meaning |
|---|---|---|
.relaxed |
all operations | only atomicity; no promise about other memory |
.acquiring |
loads, updates | after reading a value written with .releasing, this thread sees everything the writer wrote before that store |
.releasing |
stores, updates | writes made before this store become visible to a thread that reads it with .acquiring |
.acquiringAndReleasing |
updates | both at once, for read-modify-write operations like compareExchange |
.sequentiallyConsistent |
all operations | acquiring and releasing, plus all sequentially consistent operations appear in one order that every thread agrees on |
The types enforce the "allowed on" column. load takes an AtomicLoadOrdering, store takes an AtomicStoreOrdering, and read-modify-write operations take an AtomicUpdateOrdering. Writing load(ordering: .releasing) doesn't compile.
The classic use of acquiring and releasing is publishing data. One thread fills in data and then sets a flag with .releasing. Another thread waits for the flag with .acquiring and can then safely read the data:
import Foundation
import Synchronization
// plain, non-atomic data, protected only by the `ready` flag
nonisolated(unsafe) var settings: [String: String] = [:]
let ready = Atomic<Bool>(false)
func producer() {
settings = ["theme": "dark", "lang": "pl"]
ready.store(true, ordering: .releasing) // publish everything written above
}
func consumer() -> [String: String] {
while !ready.load(ordering: .acquiring) { // pairs with the .releasing store
Thread.sleep(forTimeInterval: 0.001)
}
return settings // sees the producer's writes
}
@main
struct App {
static func main() {
let done = DispatchSemaphore(value: 0)
Thread {
let s = consumer()
print("consumer got", s.sorted { $0.key < $1.key })
done.signal()
}.start()
Thread { producer() }.start()
done.wait()
}
}
Output:
consumer got [(key: "lang", value: "pl"), (key: "theme", value: "dark")]
With .relaxed on both sides, the flag itself would still be read correctly. But the language would no longer promise that the consumer sees the dictionary that was written before the flag. nonisolated(unsafe) turns off the compiler's checks for settings, so the orderings are the only thing that keeps this code correct. Code like this is easy to get wrong. In most programs a Mutex around the data is the better choice.
Guidelines:
- Counters, statistics, IDs and other values that nothing else depends on:
.relaxed. - A flag or pointer that publishes other data:
.releasingfor the store,.acquiringfor the load. - Read-modify-write operations that both observe and publish data, like
compareExchangeon a state machine:.acquiringAndReleasing. - If you are not sure:
.sequentiallyConsistent. It is the strongest and easiest to reason about.
AtomicLazyReference
AtomicLazyReference<Instance> holds an optional class reference that is set at most once. It is a lock-free way to create a shared object lazily:
import Foundation
import Synchronization
final class Config: Sendable {
let values: [String: String]
init() {
print("loading config")
values = ["region": "eu"]
}
}
let sharedConfig = AtomicLazyReference<Config>()
func config() -> Config {
if let existing = sharedConfig.load() {
return existing
}
// several threads may get here and each create a Config,
// but only the first storeIfNil wins; the rest get the winner back
return sharedConfig.storeIfNil(Config())
}
@main
struct App {
static func main() {
let ids = Mutex<Set<ObjectIdentifier>>([])
DispatchQueue.concurrentPerform(iterations: 100) { _ in
let c = config()
ids.withLock { _ = $0.insert(ObjectIdentifier(c)) }
}
print("distinct instances used:", ids.withLock { $0.count })
print("region:", config().values["region"]!)
}
}
Output:
loading config
distinct instances used: 1
region: eu
Every thread gets the same instance. But the initializer can run more than once. In 20 runs of this program, 19 printed loading config once and one printed it 8 times. If the initializer is expensive or has side effects, use a static let (Swift initializes globals and static properties lazily and exactly once) or create the object under a Mutex.
Summary
import Synchronizationgives youMutexandAtomic. They are in Swift 6.0 on all platforms, and need macOS 15 / iOS 18 or newer on Apple platforms.Mutex(value)owns the data it protects. You reach the data only throughwithLock { }, which can return a value and rethrow (typed) errors.withLockIfAvailabledoesn't wait.- A
final classwith aletMutexproperty can be plainSendable. You don't need@unchecked. - Never
awaitinside the lock (the compiler won't let you). Keep critical sections short, and don't lock the same mutex recursively. - Pick a
Mutexfor short, synchronous access from anywhere. Pick an actor when callers are async anyway and operations may suspend. Atomic<Value>gives lock-freeload,store,exchange,compareExchange,wrappingAdd,min/maxand bit operations on integers,Bool, pointers andAtomicRepresentableenums.- Every atomic operation names its memory ordering.
.relaxedis right for counters. Use.releasing/.acquiringpairs when an atomic publishes other data, and.sequentiallyConsistentwhen in doubt. - Both types are
~Copyable, because a copied lock or atomic would no longer be shared. Store them inletproperties of classes, in globals, or in other~Copyabletypes. - See Actors for the async alternative, and async and await for the basics of Swift concurrency.