With GCD, how does a .barrier work item on a custom concurrent DispatchQueue protect a thumbnail cache that many queues read and one writes?
answer
- a reader-writer lock in queue form
- sync reads, async writes
- the barrier waits for earlier items
- only a queue created with .concurrent
- global queues ignore the barrier flag
basics
~20 sReads run with queue.sync on a custom concurrent queue, so many proceed at once; writes use queue.async(flags: .barrier), which waits for earlier items, runs alone, then lets later items continue. The flag only works on a queue you created with .concurrent.
solid answer
~50 sGive the cache a private queue created with `DispatchQueue(label:attributes: .concurrent)`. Reads go through `queue.sync { images[key] }`: they return the value to the caller and may overlap one another. Writes go through `queue.async(flags: .barrier) { images[key] = data }`. A barrier item does not start until every item submitted before it has finished, then runs by itself, and items submitted after it wait until it completes, so no read ever sees the dictionary mid-write. Writes are async so callers do not block. The libdispatch header sums it up: a serial queue is GCD's mutex, a concurrent queue with barriers is its reader-writer lock. The barrier only behaves specially on a queue you created with `.concurrent`; on a global queue or a serial queue it runs like any other item, so a barrier sent to `DispatchQueue.global()` protects nothing.
code
swift · 17 linesimport Foundation
final class ThumbnailCache: @unchecked Sendable {
private var images: [String: Data] = [:]
private let queue = DispatchQueue(label: "com.example.thumbnails",
attributes: .concurrent)
func image(for key: String) -> Data? {
queue.sync { images[key] } // readers run side by side
}
func store(_ data: Data, for key: String) {
queue.async(flags: .barrier) { // the writer runs alone
self.images[key] = data
}
}
}go deeper
Recall that a barrier is a flag on a work item, written queue.async(flags: .barrier), and that the cache's reads use sync while its writes use the barrier.
Explain the ordering a barrier imposes on earlier and later items, why it needs a custom queue created with .concurrent, and why reads are sync and writes async.
Spot the broken variants in review: a barrier on a global queue, a sync call from inside the cache queue, and urgent writes starved by low-priority readers.
Decide between a serial queue, a barrier queue and a lock for shared caches, and which of those caches a migration should turn into an actor first.
## The problem in one cache A stargazing app keeps decoded **thumbnails** of star charts in a dictionary. Many parts of the app read from it at once, from different queues, and occasionally one of them stores a new thumbnail. A Swift `Dictionary` is not safe to mutate while another thread reads it, so unsynchronised access is a **data race** that can corrupt the dictionary or crash. GCD offers two queue-based ways to guard it: - a **serial queue**, through which every read and write passes one at a time; - a **custom concurrent queue with barrier writes**, which lets reads overlap and gives writes exclusive access. The libdispatch header for concurrent queues puts it directly: if a serial queue is the Dispatch equivalent of a mutex, a concurrent queue is the equivalent of a reader-writer lock, where regular items are readers and barriers are writers. ## What a barrier does to the queue When you submit a work item with `flags: .barrier` to a concurrent queue you created, the queue changes its behaviour around that item: 1. Items submitted **before** the barrier keep running until each has finished. 2. The barrier item then runs **by itself**; nothing else on that queue runs beside it. 3. Items submitted **after** the barrier wait until it completes. 4. Once the barrier finishes, the queue goes back to running items concurrently. A barrier does not interrupt anything: reads already running finish first, which is exactly what makes the write safe. ## Only on your own concurrent queue The flag is meaningful only on a queue created with the `.concurrent` attribute. The libdispatch header for the barrier API says that on a global queue, or on a queue not created as concurrent, barrier blocks behave exactly like blocks submitted with the normal `async` or `sync` calls. So a barrier sent to `DispatchQueue.global()` can start while an earlier item is still running, while the same barrier on a custom concurrent queue waits for it. This is the most common bug in this pattern: someone writes `DispatchQueue.global().async(flags: .barrier)` and believes the cache is protected. ## Writing the cache The snippet below follows four rules: - **Reads use `sync`**, because the caller needs the value back, and plain items on a concurrent queue may overlap one another. - **Writes use `async(flags: .barrier)`**, so the caller does not block while earlier reads drain. - The queue and the dictionary are **private**, so nothing can bypass the queue. - Nothing inside a work item calls `queue.sync` on the same queue: a thread waiting on a queue it is already running deadlocks. In the Swift 6 language mode a class like this is typically marked `@unchecked Sendable` so other isolation domains may share it, because the compiler cannot see that the queue protects the dictionary; that marking is a promise the queue discipline must keep. ## Check-then-act belongs inside one barrier Separate safe reads and safe writes do not make a compound operation safe. A common bug in this cache is "store the thumbnail only if none is cached yet", written as a `sync` read followed by a barrier write: 1. Two queues each read the key through `sync` and both see `nil`. 2. Both decode the same chart image. 3. Both submit a barrier write, and the second silently replaces the first. The fix is to do the whole decision inside a single barrier block: look up the key, and only store when it is still missing. Because the barrier runs alone, no other read or write can slip in between the check and the act. The same rule covers counters, "append if absent" lists and any update computed from the current value. ## Serial queue or barrier? | | Serial queue | Concurrent queue with barrier writes | |---|---|---| | Reads overlap | no | yes | | Writes exclusive | yes | yes | | Works on a global queue | not applicable | no, needs a custom `.concurrent` queue | | Cost | lowest | a little more bookkeeping per item | | Fits | short critical sections, write-heavy access | read-heavy caches with rare writes | When reads are cheap and rare, a serial queue is simpler and often just as fast. The barrier pays off when many reads would otherwise queue up behind each other. ## Pitfalls and limits - **Priority**: the libdispatch header notes that concurrent queues currently do not implement priority inversion avoidance when lower-priority readers keep a higher-priority barrier from running. A flood of low-QoS reads can delay an urgent write. - **Reading inside a barrier block** is fine; calling `queue.sync` from inside it is a deadlock. - **OperationQueue** offers `addBarrierBlock(_:)`, available since iOS 13, which the header describes as similar to `dispatch_barrier_async`: it runs after all operations already enqueued finish, and later operations wait for it.
- Why are the writes async but the reads sync?A read must hand its value back, so `sync` is the natural shape, and plain items on a concurrent queue still overlap, so readers do not wait for each other. A write returns nothing; making it `async` lets the caller continue while earlier reads drain and the barrier runs. A synchronous barrier would block every writer for that whole time.
- Can a high-priority write get stuck behind low-priority reads?Yes. The libdispatch header for concurrent queues notes that they do not currently implement priority inversion avoidance when lower-priority readers are running and keep a higher-priority barrier from being invoked. Keep reads short and give the cache's queue a quality of service that suits its most urgent caller.
- What does OperationQueue offer for the same pattern?`addBarrierBlock(_:)`, available since iOS 13: the block runs after every operation already enqueued has finished, and operations added later do not start until it completes. The header calls it similar to `dispatch_barrier_async`. It suits an operation-based pipeline; for a plain dictionary cache the GCD barrier is lighter.
A barrier is a museum gallery closing to re-hang a painting: visitors already inside finish and leave, the curator works alone, and the visitors queued at the door go in only after the curator is done.
- A .barrier item on DispatchQueue.global() blocks other work on the global queue.
- A barrier item interrupts reads that are already running on the queue.
- Reads need the barrier flag too, or they will see half-written data.
- queue.sync from inside the cache queue's own work item is a safe way to read.
- A serial queue cannot guard a cache because it cannot return values.