<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Master iOS Concurrency - Medium]]></title>
        <description><![CDATA[Master iOS Concurrency with Async/Await, Actors, Task Groups, GCD, structured concurrency, thread safety, performance tuning, and real-world architecture patterns for modern Swift applications. - Medium]]></description>
        <link>https://medium.com/master-ios-concurrency?source=rss----c379d6f0cd70---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Master iOS Concurrency - Medium</title>
            <link>https://medium.com/master-ios-concurrency?source=rss----c379d6f0cd70---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:55:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/master-ios-concurrency" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ Concurrency in iOS — Part 2(c): Debugging Concurrency in Swift]]></title>
            <link>https://medium.com/master-ios-concurrency/concurrency-in-ios-part-2-c-debugging-concurrency-in-swift-b4f330b46460?source=rss----c379d6f0cd70---4</link>
            <guid isPermaLink="false">https://medium.com/p/b4f330b46460</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Anubhav Giri]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 06:14:34 GMT</pubDate>
            <atom:updated>2026-06-12T06:14:36.163Z</atom:updated>
            <content:encoded><![CDATA[<h3>Concurrency in iOS — Part 2(c): Debugging Concurrency in Swift</h3><p><em>“If concurrency is about design, debugging is about reality.”</em></p><p>Concurrency bugs are silent killers.<br>They appear randomly, vanish under the debugger, and hide behind async boundaries.<br>Traditional breakpoints won’t save you — you need runtime tools and disciplined analysis.</p><h3>💡 Why Concurrency Bugs Are Different</h3><p>Unlike crashes that happen immediately, concurrency issues:</p><ul><li>Surface <strong>nondeterministically</strong> (timing-dependent)</li><li><strong>Disappear</strong> when you attach a debugger</li><li><strong>Hide</strong> behind actor isolation and async boundaries</li></ul><p>You need <strong>runtime inspection</strong>, not just code review.</p><h3>🧰 Tool #1: Thread Sanitizer (TSan)</h3><p><strong>Thread Sanitizer (TSan)</strong> is your first line of defense against <strong>data races</strong> — simultaneous unsynchronized reads/writes to shared memory.</p><h3>🧭 How to Enable</h3><p><strong>Xcode → Scheme → Run → Diagnostics → ✔︎ Thread Sanitizer</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XFUZL6JYzE9_DCrWMlNuUw.png" /></figure><ul><li><strong>Cost:</strong> 3–5× slower debug runs (only in Debug builds)</li><li><strong>Benefit:</strong> Detects races you’d never catch manually</li></ul><h3>⚙️ Example Problem</h3><pre>final class UnsafeCounter {<br>    var value = 0<br>    func increment() { value += 1 }<br>}<br><br>let counter = UnsafeCounter()<br>DispatchQueue.concurrentPerform(iterations: 1_000) { _ in <br>    counter.increment()<br>}</pre><h3>🚨 TSan Output</h3><pre>Thread Sanitizer: data race on variable &#39;value&#39;<br>Write of size 8 by thread T1<br>Previous write by thread T2</pre><h3>✅ The Fix</h3><pre>actor SafeCounter {<br>    private var value = 0<br>    func increment() { value += 1 }<br>}</pre><h3>🧩 What TSan Catches</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hRRYf-6vokx1m52M8Pleww.png" /></figure><blockquote><strong><em>Note:</em></strong><em> TSan operates at the </em>memory-access<em> level, detecting unsynchronized concurrent access regardless of whether you use GCD, Swift Concurrency, or manual threading.<br>It doesn’t understand high-level semantics like actor isolation — it only sees whether memory accesses are properly synchronized.</em></blockquote><blockquote><strong><em>Gotcha:</em></strong><em> TSan may report false positives with lock-free algorithms using atomics.<br>Use </em><em>__tsan_acquire() and </em><em>__tsan_release() annotations for custom synchronization primitives.</em></blockquote><h3>🧭 Tool #2: Deadlock &amp; Livelock Debugging</h3><p>Even when TSan passes, your app can still freeze or hang indefinitely.<br>Here are the most common culprits.</p><h3>⚠️ Issue #1: Sync on Same Queue (Deadlock)</h3><pre>let queue = DispatchQueue(label: &quot;serial&quot;)<br><br>queue.sync {<br>    queue.sync { print(&quot;deadlock&quot;) } // ❌ Freeze!<br>}</pre><p><strong>Why it happens:</strong><br>The outer sync blocks the queue while waiting for the inner block,<br>and the inner block waits for the queue to be free — a classic deadlock.</p><p><strong>✅ Solution:</strong> Use async for nested work, or dispatch to a different queue.</p><h3>⚠️ Issue #2: Actor Suspension Cycles (Livelock)</h3><pre>actor A { <br>    var b: B?<br>    func ping() async { await b?.pong() }<br>}<br><br>actor B { <br>    var a: A?<br>    func pong() async { await a?.ping() }<br>}<br><br>// Setup: a.b = b; b.a = a<br>// Trigger: await a.ping()</pre><p><strong>🚨 Problem:</strong> Infinite suspension loop — both actors keep awaiting each other forever.<br>This is a <strong>livelock</strong>, not a traditional deadlock.<br>Tasks remain “running” from the runtime’s perspective, but they make no progress.</p><p><strong>Why actors don’t deadlock:</strong><br>Swift actors are <em>reentrant</em> — they don’t hold a thread lock during suspension.<br>This prevents thread-level deadlocks but allows <strong>suspension cycles</strong> where tasks indefinitely await each other.</p><p><strong>✅ Solution:</strong></p><ul><li>Design <strong>acyclic</strong> communication patterns</li><li>Use a <strong>coordinator actor</strong> to break cycles</li><li>Add <strong>timeout</strong> mechanisms for critical paths</li><li>Include <strong>cancellation checks</strong> (try Task.checkCancellation())</li></ul><h3>🧩 Tool #3: Concurrency Debugger (Xcode 15 +)</h3><p>Introduced in <strong>Xcode 15</strong>, the <strong>Concurrency Debugger</strong> visualizes your running tasks, actors, and queues in real time.</p><h3>🔍 How to Access</h3><ol><li>Run your app in <strong>Debug</strong> mode</li><li>Pause execution</li><li>Open <strong>Debug Navigator → Concurrency</strong></li></ol><h3>🖥️ What You’ll See</h3><ul><li>Active tasks grouped by actor</li><li>Each task’s await stack (where it last suspended)</li><li>Blocked tasks waiting for resources</li><li>Parent-child task hierarchies</li></ul><h3>🧠 Use Cases</h3><p>✅ Identify tasks waiting for unavailable actors<br>✅ Detect <em>task explosion</em> (too many concurrent tasks)<br>✅ Visualize main-actor bottlenecks<br>✅ Inspect long-suspended tasks for potential livelocks<br>✅ Debug actor reentrancy issues</p><blockquote><strong><em>Pro Tip:</em></strong><em> Look for tasks suspended unusually long — they often signal suspension cycles or resource contention.</em></blockquote><h3>✅ Production-Ready Checklist</h3><p>Before shipping, review your concurrency setup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPHVTVSYFJOfrttpEUmNhQ.png" /></figure><p><strong>Measure results with:</strong> Instruments → System Trace or Time Profiler</p><blockquote><strong><em>Context Switch Guidance:</em></strong><em> While &gt; 1 000/s can hint at issues, “normal” rates vary by workload.<br>Establish a baseline for your app and investigate deviations.<br>Modern systems handle thousands efficiently, but unnecessary switching still wastes CPU.</em></blockquote><h3>⚙️ 4-Step TSan Workflow</h3><ol><li><strong>Enable TSan</strong> and run integration or stress tests</li><li><strong>Resolve every warning</strong> (usually unprotected shared state)</li><li><strong>Add regression tests</strong> using concurrentPerform or task groups</li><li><strong>Profile with Instruments → System Trace:</strong></li></ol><ul><li>Monitor thread count (≤ 40 for most apps)</li><li>Observe context switch patterns</li><li>Detect thread-pool saturation</li></ul><h3>💡 Key Takeaways</h3><p>✅ TSan detects memory-level data races, not logical bugs like livelocks<br>✅ Deadlocks = cyclic blocking · Livelocks = cyclic suspension<br>✅ Avoid sync-on-same-queue and mutual actor awaits<br>✅ Concurrency Debugger reveals suspension points and bottlenecks<br>✅ Actors &gt; locks — simpler, safer, more composable<br>✅ Test under load — concurrency bugs hide in perfect conditions</p><h3>🧠 Pro Tips</h3><p>🔹 Use Task.checkCancellation() for cooperative cancellation in long-running tasks<br>🔹 Prefer structured concurrency (withTaskGroup) over fire-and-forget tasks<br>🔹 Bridge GCD → Swift Concurrency using withCheckedContinuation (<em>the standard bridge for async API interop</em>)<br>🔹 Enable TSan in your CI pipeline, not just locally<br>🔹 Use @MainActor(unsafe) cautiously — it bypasses isolation and can reintroduce races<br>🔹 For Swift 6 +, consider OSAllocatedUnfairLock or Mutex for fine-grained locking when actors are too coarse</p><h3>🚀 Next Up</h3><p><strong>Part 3 → Grand Central Dispatch Deep Dive</strong><br>We’ll explore serial vs concurrent queues, QoS, barriers, and real-world sync deadlocks.</p><p>Find this Helpful — Follow me on LinkedIn: <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01">www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4f330b46460" width="1" height="1" alt=""><hr><p><a href="https://medium.com/master-ios-concurrency/concurrency-in-ios-part-2-c-debugging-concurrency-in-swift-b4f330b46460">🧩 Concurrency in iOS — Part 2(c): Debugging Concurrency in Swift</a> was originally published in <a href="https://medium.com/master-ios-concurrency">Master iOS Concurrency</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency in iOS — Part 3(a): Foundations of Grand Central Dispatch (GCD)]]></title>
            <link>https://medium.com/master-ios-concurrency/concurrency-in-ios-part-3-a-foundations-of-grand-central-dispatch-gcd-43343a45dc11?source=rss----c379d6f0cd70---4</link>
            <guid isPermaLink="false">https://medium.com/p/43343a45dc11</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Anubhav Giri]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 06:13:44 GMT</pubDate>
            <atom:updated>2026-06-12T06:13:45.358Z</atom:updated>
            <content:encoded><![CDATA[<h3>Concurrency in iOS — Part 3(a): Foundations of Grand Central Dispatch (GCD)</h3><blockquote><em>“If Swift Concurrency is the autopilot, GCD is the engine room that powers it.”</em></blockquote><p>Before async/await, before Task or actor, there was <strong>GCD — the silent workhorse</strong> still running everything beneath Swift Concurrency.<br>This part is your guided tour of that engine room: how <strong>Dispatch Queues</strong> work, how tasks hop across CPU cores, and why mastering GCD makes you a stronger iOS engineer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*SJ0VuJfLLEztAunM0XVVsA.png" /></figure><h3>🔍 What Exactly Is GCD?</h3><p><strong>Grand Central Dispatch (GCD)</strong> is Apple’s low-level concurrency framework written in C, sitting atop the <strong>Darwin kernel</strong> and <strong>Mach threads</strong>.<br>It manages <strong>thread pools</strong>, schedules work, handles <strong>priorities</strong>, and even saves battery by distributing tasks across the right cores.</p><p>Instead of you juggling threads manually, GCD:</p><ul><li>Manages thread pools</li><li>Optimizes task scheduling</li><li>Chooses CPU cores dynamically</li><li>Balances performance vs energy</li></ul><pre>DispatchQueue.global().async {<br>    runSomeBackgroundWork()<br>}</pre><p>Every time you write code like that, you’re letting <strong>GCD</strong> decide <strong>which thread, which CPU core, and which QoS level</strong>should execute that closure.<br>GCD wraps that closure into a <em>work item</em>, drops it into a <em>queue</em>, and the kernel decides which core should execute it.</p><p>And here’s the key: <strong>Swift Concurrency (</strong><strong>Task, </strong><strong>await) is built on top of these same queues.</strong></p><h3>⚛️ 1. Atomicity — The Hidden Villain</h3><p>Before learning how queues work, we must talk about <strong>atomicity</strong> — the root cause of most GCD bugs.</p><blockquote><em>An operation is </em><strong><em>atomic</em></strong><em> if it’s indivisible — either it happens entirely or not at all.</em></blockquote><h3>⚠️ The Classic Race</h3><pre>final class Counter {<br>    var value = 0<br><br>    func increment() {<br>        value += 1   // read → modify → write (NOT atomic)<br>    }<br>}<br><br>let counter = Counter()<br><br>DispatchQueue.concurrentPerform(iterations: 1000) { _ in<br>    counter.increment()<br>}<br><br>print(counter.value) // ❌ Could be 998 or 999 — race condition</pre><p>value += 1 breaks down into multiple CPU instructions (LOAD → ADD → STORE).<br>If two threads interleave these steps, increments are lost.</p><h3>✅ Fix #1 — Serial Queue Isolation</h3><p>Use a <strong>private serial queue</strong> to make access atomic.</p><pre>final class SafeCounter {<br>    private let queue = DispatchQueue(label: &quot;com.app.counter.isolation&quot;)<br>    private var value = 0<br><br>    // Synchronous read - blocks caller until retrieved<br>    var newValue: Int {<br>        queue.sync {<br>            value<br>        }<br>    }<br><br>    // Asynchronous write - returns immediately<br>    func increment() {<br>        queue.async {<br>            self.value += 1<br>        }<br>    }<br><br>    // Synchronous write - waits until complete<br>    func incrementSync() {<br>        queue.sync {<br>            self.value += 1<br>        }<br>    }<br>}</pre><h4>⚠️ Usage Considerations</h4><pre>let counter = SafeCounter()<br>counter.increment()<br>print(counter.newValue) // ❌ Might print 0 — async hasn&#39;t finished yet<br><br>counter.incrementSync()<br>print(counter.newValue) // ✅ Prints 1 — write completed<br><br>counter.increment()<br>DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {<br>    print(counter.newValue) // ✅ Gives time for async write<br>}</pre><p>💡 <strong>Key Takeaway</strong></p><p>This pattern is known as <strong>Reader–Writer Isolation</strong>:</p><ul><li>async writes → fire-and-forget</li><li>sync writes → block until done</li><li>Choose based on whether you need immediacy or throughput.</li></ul><h3>⚙️ Fix #2 — Concurrent Queue + Barrier</h3><p>When reads far outnumber writes, use a <strong>concurrent queue</strong> with <strong>barrier writes</strong>.</p><pre>final class ConcurrentCounter {<br>    private let queue = DispatchQueue(label: &quot;com.app.counter.concurrent&quot;, attributes: .concurrent)<br>    private var value = 0<br>    <br>    var newValue: Int {<br>        queue.sync { value }<br>    }<br>    <br>    func getValue(completion: @escaping (Int) -&gt; Void) {<br>        queue.async {<br>            completion(self.value)<br>        }<br>    }<br>    <br>    func increment() {<br>        queue.async(flags: .barrier) {<br>            self.value += 1<br>        }<br>    }<br>}</pre><h4>📊 Usage Patterns</h4><pre>let counter = ConcurrentCounter()<br><br>// 1️⃣ Blocking read<br>print(counter.newValue)<br><br>// 2️⃣ Async read<br>counter.getValue { print($0) }<br><br>// 3️⃣ Parallel reads<br>for _ in 1...100 {<br>    counter.getValue { print($0) }<br>}</pre><p>💡 <strong>Trade-offs</strong></p><ul><li>Sync reads = simple but blocking (avoid on main)</li><li>Async reads = non-blocking, callback-based</li><li>Best modern solution = async/await (coming in Part 3b)</li></ul><p>Perfect for <strong>caches or shared configuration objects.</strong></p><h3>🚧 Barrier Flag Caveat</h3><pre>// ✅ Works on custom concurrent queues<br>let custom = DispatchQueue(label: &quot;com.app.custom&quot;, attributes: .concurrent)<br><br>custom.async(flags: .barrier) {<br>    print(&quot;Exclusive access on custom queue&quot;)<br>}<br><br>// ❌ Ignored on global queues<br>DispatchQueue.global().async(flags: .barrier) {<br>    print(&quot;⚠️ Barrier ignored - global queues are shared system-wide&quot;)<br>}</pre><blockquote><strong><em>Critical Rule:</em></strong><em> Barriers only provide exclusivity on </em><strong><em>custom concurrent queues</em></strong><em> you create.</em></blockquote><h3>🧱 2. Serial vs Concurrent Queues = Lanes on a Highway</h3><p>Queues are the roads your code drives on 🚗.</p><h3>🛣️ Serial Queue</h3><pre>let q = DispatchQueue(label: &quot;com.app.serial&quot;)<br><br>q.async {<br>    print(&quot;Task 1&quot;)<br>}<br><br>q.async {<br>    print(&quot;Task 2&quot;)<br>}<br>// Always ordered: Task 1 → Task 2</pre><h3>🛫 Concurrent Queue</h3><pre>let q = DispatchQueue(label: &quot;com.app.concurrent&quot;, attributes: .concurrent)<br><br>q.async {<br>    print(&quot;Task A&quot;)<br>}<br><br>q.async {<br>    print(&quot;Task B&quot;)<br>}<br>// Unpredictable order - whichever starts first</pre><h3>🔄 3. sync vs async = Traffic Light Analogy</h3><pre>let q = DispatchQueue(label: &quot;com.app.demo&quot;)<br><br>q.sync  {<br>    print(&quot;Runs now - waits until done&quot;)<br>}<br><br>q.async {<br>    print(&quot;Runs later - caller continues&quot;)<br>}</pre><p>🧭 Remember:</p><ul><li><strong>Serial vs Concurrent</strong> → how the queue behaves</li><li><strong>Sync vs Async</strong> → how the caller behaves</li><li>🚦 Serial/concurrent = lanes</li><li>⏱️ Sync/async = stoplight</li></ul><h3>🧵 4. The Main Queue — Your UI’s Heartbeat</h3><p>The <strong>main queue</strong> is tied to the <strong>main thread</strong> — the only lane that touches UIKit or SwiftUI.<br>Block it → frozen UI. Over-dispatch to it → lag.</p><pre>// ❌ Unnecessary dispatch<br>DispatchQueue.main.async {<br>    updateUI() // Already on main thread<br>}<br><br>// ✅ Correct<br>updateUI()</pre><p>When returning from background work:</p><pre>DispatchQueue.global().async {<br>    let data = fetchData()<br>    <br>    DispatchQueue.main.async {<br>        updateUI(with: data)<br>    }<br>}</pre><p>💡 <strong>Golden Rule:</strong><br>Touch UI only from main queue — but don’t double-dispatch if you’re already there.</p><h3>⚙️ Bonus Tip — Safest Way to Run on Main Thread</h3><p>Sometimes callbacks run on unknown threads. Use a helper 👇</p><pre>extension Thread {<br>    static func runOnMain(_ block: @escaping () -&gt; Void) {<br>        if Thread.isMainThread { <br>            block() <br>        } else {<br>            DispatchQueue.main.async(execute: block)<br>        }<br>    }<br>}<br><br>// ✅ Usage<br>Thread.runOnMain {<br>    myLabel.text = &quot;Updated on main thread&quot;<br>}</pre><p>💡 Checks Thread.isMainThread; dispatches only if needed.<br>Prefer this to blindly calling DispatchQueue.main.async.</p><h3>⚙️ 5. Why GCD Still Matters in 2025</h3><p>Even in the age of <strong>Swift Concurrency</strong>, <strong>GCD remains the engine beneath the autopilot.</strong><br>Every Task {} you create ultimately becomes a <strong>GCD block running on a Mach thread.</strong></p><blockquote><strong><em>GCD uses a shared, system-managed worker thread pool.</em></strong><em><br>Work from many queues is scheduled onto those threads; queues do </em><strong><em>not</em></strong><em> have dedicated threads or pools.<br>The </em><strong><em>main queue</em></strong><em> is the exception — it’s permanently bound to the process’s main thread.</em></blockquote><h3>🧠 What’s Actually True About GCD Threads &amp; Queues</h3><ul><li><strong>No 1:1 mapping</strong> — queues aren’t backed by private pools.</li><li><strong>Shared pool</strong> — libdispatch schedules onto a system-managed pool built atop pthread workqueues.</li><li><strong>Main exception</strong> — main queue → main thread only.</li><li><strong>Dynamic sizing</strong> — pool scales by QoS, blocking behavior, and load.</li><li><strong>Queue ≠ Thread</strong> — serial queue runs one task at a time, but on different threads over time.</li><li><strong>Root queues &amp; QoS</strong> — custom queues inherit from a small set of global root queues (userInteractive, userInitiated, utility, background) sharing the same workers.</li></ul><p>So when you understand GCD, you understand how Swift Concurrency <strong>actually runs under the hood.</strong> 🚀</p><h3>🧪 Try It Yourself 🚀</h3><pre>import Foundation<br><br>let queue = DispatchQueue(label: &quot;com.app.demo&quot;, attributes: .concurrent)<br>let group = DispatchGroup()<br><br>for i in 1...5 {<br>    group.enter()<br><br>    queue.async {<br>        print(&quot;🚀 Task \(i) on \(Thread.current)&quot;)<br>        Thread.sleep(forTimeInterval: 0.5)<br>        group.leave()<br>    }<br>}<br><br>group.notify(queue: .main) {<br>    print(&quot;✅ All tasks done on main → \(Thread.current)&quot;)<br>}</pre><p>🧩 Watch how tasks hop between threads, then the final callback lands back on main.</p><h3>⏭️ Coming Up Next — Part 3(b)</h3><p>We’ll dive deeper into GCD:</p><ul><li>Dispatch Barriers</li><li>Dispatch Groups 🧰</li><li>Quality of Service (QoS) ⚙️</li><li>Kernel scheduling 🧩</li><li>Debugging with Instruments &amp; TSan 🔍</li></ul><h3>🧠 Series Index</h3><p>1️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-1-from-cpu-cores-to-mach-threads-and-thread-pools-d1ebd31ef138">Part 1 — From CPU Cores to Mach Threads</a><br>2️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-a-thread-safety-synchronisation-mechanics-42f9714b8cf2">Part 2(a) — Thread Safety &amp; Synchronization</a><br>3️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-b-actors-isolation-in-swift-concurrency-ec2d567118dc">Part 2(b) — Actors &amp; Isolation in Swift Concurrency</a><br>3️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-c-debugging-concurrency-in-swift-b4f330b46460">Part 2(c) — Debugging Concurrency in Swift</a><br>4️⃣ <strong>Part 3(a) — Inside GCD (Foundations)</strong> <em>(you are here)</em><br>5️⃣ Part 3(b) — Advanced GCD Patterns &amp; Performance <em>(coming soon)</em></p><p>Find this Helpful — Follow me on LinkedIn: <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01">www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43343a45dc11" width="1" height="1" alt=""><hr><p><a href="https://medium.com/master-ios-concurrency/concurrency-in-ios-part-3-a-foundations-of-grand-central-dispatch-gcd-43343a45dc11">Concurrency in iOS — Part 3(a): Foundations of Grand Central Dispatch (GCD)</a> was originally published in <a href="https://medium.com/master-ios-concurrency">Master iOS Concurrency</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency in iOS — Part 3(b): Practical Thread-Safety Patterns in GCD + LLD Insights]]></title>
            <link>https://medium.com/master-ios-concurrency/concurrency-in-ios-part-3-b-practical-thread-safety-patterns-in-gcd-lld-insights-99cfe665e386?source=rss----c379d6f0cd70---4</link>
            <guid isPermaLink="false">https://medium.com/p/99cfe665e386</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Anubhav Giri]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 06:13:16 GMT</pubDate>
            <atom:updated>2026-06-12T06:13:17.248Z</atom:updated>
            <content:encoded><![CDATA[<h3>Concurrency in iOS — Part 3(b): Practical Thread-Safety Patterns in GCD + LLD Insights</h3><blockquote>“Writing concurrent code is easy. Writing safe concurrent code is engineering.”</blockquote><p>In <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-3-a-foundations-of-grand-central-dispatch-gcd-43343a45dc11">Part 3(a)</a> we explored the foundations of Grand Central Dispatch (GCD) — queues, sync vs async, and atomicity.<br>Now we’ll turn theory into practice: how to build safe, predictable concurrent systems with GCD — and what’s really happening under the hood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*9YOVgUF-GM-FauxtA4O2JA.png" /></figure><h3>1️⃣ Serial Queue Pattern — Safe State Isolation</h3><p>A serial queue executes one task at a time — your simplest mutex replacement.</p><pre>final class SafeCounter {<br>    private let queue = DispatchQueue(label: &quot;com.app.counter.isolation&quot;)<br>    private var value = 0<br>   <br>    var newValue: Int {<br>        queue.sync { value }<br>    }<br>    <br>    func increment() {<br>        queue.sync {<br>            value += 1<br>        }<br>    }<br>}</pre><p>🧠 <strong>LLD Insight</strong></p><ul><li>queue.sync enqueues a block and <strong>blocks the caller</strong> until execution completes.</li><li>Internally, GCD uses a <strong>FIFO semaphore</strong> for serial ordering — a lightweight mutex.</li><li>Each .sync introduces a <strong>memory barrier</strong>, ensuring cache coherency and preventing CPU reordering.</li></ul><h3>⚠️ Mixing .sync and .async = Timing Issue ( Not a Race )</h3><pre>final class MixedCounter {<br>    private let queue = DispatchQueue(label: &quot;counter&quot;)<br>    private var value = 0<br>    <br>    var newValue: Int {<br>        queue.sync { value }<br>    }       // sync read<br>    <br>    func increment() {<br>        queue.async {<br>            value += 1<br>        }<br>    } // async write<br>}<br><br>let c = MixedCounter()<br>c.increment()<br>print(c.newValue)  // may print 0 or 1 ( non-deterministic )</pre><p>✅ Thread-safe (because serialized), but order is unpredictable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0gwVwPCfbtaPUIjtAloOcg.png" /></figure><h3>2️⃣ Concurrent Queue + Barrier — Controlled Parallelism</h3><p>Parallel reads, exclusive writes = best of both worlds.</p><pre>final class ConcurrentCache {<br>    private let queue = DispatchQueue(<br>        label: &quot;com.app.cache.concurrent&quot;,<br>        attributes: .concurrent<br>    )<br>    private var storage: [String: Data] = [:]<br>    <br>    func get(_ key: String) -&gt; Data? {<br>        queue.sync {<br>            storage[key]<br>        }<br>    }<br>    <br>    func getAsync(_ key: String, completion: @escaping (Data?) -&gt; Void) {<br>        queue.async {<br>            completion(self.storage[key])<br>        }<br>    }<br>    <br>    func set(_ data: Data, for key: String) {<br>        queue.async(flags: .barrier) {<br>            self.storage[key] = data<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CkpPWcmSLVwsUX6N2ndirw.png" /></figure><p>🧠 <strong>LLD Insight</strong></p><ul><li>Barriers map to dispatch_barrier_async_f, implementing a readers–writer lock.</li><li>Waits for all in-flight tasks, runs exclusively, then resumes queued reads.</li><li>Both sync and async reads see committed writes — the difference is <em>when</em> they execute.</li></ul><h3>3️⃣ Why Barriers Don’t Work on Global Queues</h3><pre>DispatchQueue.global().async(flags: .barrier) {<br>    print(&quot;Ignored — root queues don’t support barriers&quot;)<br>}</pre><p>🧠 <strong>LLD Insight</strong></p><ul><li>Global queues are <strong>root queues</strong> managed by the system.</li><li>Barriers only apply to <strong>target queues</strong> (queues you own).</li><li>Blocking a root queue would freeze system-wide concurrency, so GCD silently ignores the flag.</li></ul><blockquote><strong><em>Analogy:</em></strong><em> You can lock your room (custom queue), not the whole building (global queue).</em></blockquote><h3>4️⃣ Deadlocks — How They Actually Happen</h3><pre>let q = DispatchQueue(label: &quot;data&quot;) <br><br>q.async {<br>  q.sync { } // ☠️ Deadlock<br>}</pre><p>🧠 Thread T1 holds queue q, calls sync, blocks waiting for itself → circular wait.</p><h3>🧩 Classic Rules</h3><p>1️⃣ Never call .sync on the same queue you’re on.<br>2️⃣ Never call .sync on .main from the main thread.<br>3️⃣ Avoid cross-queue nested syncs (A→B→A).</p><p>✅ <strong>Catch early with preconditions</strong></p><pre>dispatchPrecondition(condition: .onQueue(dbQueue))<br>dispatchPrecondition(condition: .notOnQueue(.main))</pre><p><strong>When to Use Preconditions</strong></p><ul><li>✅ Development: always in internal APIs to catch violations.</li><li>✅ Production Selective: critical invariants (DB writes, state mutations).</li><li>❌ Avoid in hot paths or user-facing code — use logging instead.</li></ul><h3>5️⃣ Quality of Service (QoS) — Priority with Precision</h3><pre>let uiQueue = DispatchQueue(label: &quot;ui.images&quot;, qos: .userInitiated)<br>let bgQueue = DispatchQueue(label: &quot;sync.images&quot;, qos: .background)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HnAl0lUxWeS-X1KJ_2yZFg.png" /></figure><h3>🧩 QoS Inheritance and UI Lag</h3><pre>// ❌ Problem: Background QoS propagates to UI updates<br>DispatchQueue.global(qos: .background).async {<br>  let data = fetchData()<br>  <br>DispatchQueue.main.async {<br>    updateUI(data) // ⚠️ Inherits .background → UI lag<br>  }<br>}<br><br>//-------Fix--------//<br><br>// ✅ Fix: Override QoS for UI work<br>DispatchQueue.global(qos: .background).async {<br>  let data = fetchData()<br>  <br>  DispatchQueue.main.async(qos: .userInitiated) {<br>    updateUI(data) // ✅ Proper priority<br>  }<br>}<br><br>// sample methods<br>func fetchData() -&gt; Data { return Data() } <br>func updateUI(_ data: Data) { }</pre><h3>🧠 Override Semantics</h3><p>.async(qos:) <strong>overrides the inherited QoS for that block</strong>.<br> If the current QoS is higher, it won’t downgrade; if lower, it promotes.<br> Use this to guarantee UI-critical callbacks always run at the right priority.</p><h3>⚙️ QoS Promotion</h3><p>If a high-QoS task waits on low-QoS work, the system temporarily boosts the lower task to avoid priority inversion.</p><h3>6️⃣ concurrentPerform — Parallel Loops Done Right</h3><pre>DispatchQueue.concurrentPerform(iterations: 500) { i in<br>  heavyComputation(i)<br>}</pre><p>🧠 <strong>LLD Insight</strong></p><ul><li>Internally uses dispatch_apply_f.</li><li>Employs <strong>work-stealing</strong> and <strong>stride scheduling</strong> across the global thread pool.</li><li>Calling thread participates.</li><li>Best for CPU-bound work ≥ 10–15 iterations; avoid for I/O.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZX8E2KkjJnIPH_9ydAUNsA.png" /></figure><h3>7️⃣ Playground Demo — Thread Reuse in Action</h3><pre>let queue = DispatchQueue(<br>    label: &quot;com.demo.threadReuse&quot;,<br>    attributes: .concurrent<br>)<br><br>// Create a DispatchGroup to synchronize tasks<br>let group = DispatchGroup()<br><br>// Submit multiple async tasks<br>for i in 1...5 {<br>    group.enter()<br><br>    queue.async {<br>        let t = Thread.current<br>        print(&quot;⚙️ Task \(i) on \(t)&quot;)<br><br>        // Hold the thread briefly to show reuse behavior<br>        Thread.sleep(forTimeInterval: 0.5)<br><br>        group.leave()<br>    }<br>}<br><br>// Wait for all tasks to complete before exiting<br>group.wait()<br>print(&quot;✅ All tasks completed&quot;)<br><br>/* <br>  showing that some tasks share the same thread,  <br>  demonstrating thread reuse by GCD’s thread pool <br>*/<br>⚙️ Task 1 on &lt;NSThread: 0x600003f84240&gt;{number = 3, name = (null)}<br>⚙️ Task 2 on &lt;NSThread: 0x600003f84240&gt;{number = 3, name = (null)}<br>⚙️ Task 3 on &lt;NSThread: 0x600003f84d80&gt;{number = 5, name = (null)}<br>...<br>✅ All tasks completed</pre><p>💡 You’ll notice some tasks share threads — GCD reuses threads efficiently from its pool.</p><h3>📊 Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5AdrDEu5Cy-Sb3z62jccVg.png" /></figure><h3>🚨 Top 5 GCD Mistakes ( + Fixes )</h3><p>1️⃣ Using barriers on global queues → ❌<br>2️⃣ Nested .sync calls → ❌<br>3️⃣ concurrentPerform on main → ❌<br>4️⃣ Forgetting QoS inheritance → ❌<br>5️⃣ Over-using .sync → ❌</p><p>✅ Fix: custom queues, async patterns, explicit QoS overrides.</p><h3>⏭️ Coming Next — Part 3(c): GCD Under the Hood</h3><ul><li>Target queue hierarchies (queue → target → root)</li><li>Thread pool sizing and oversubscription</li><li>Memory barriers and CPU cache coherency</li><li>Dispatch object lifecycle (ARC and retains)</li><li>Performance tuning + Swift Concurrency migration</li></ul><blockquote>Mastering GCD isn’t just about using queues — it’s about understanding how your code hits the CPU.</blockquote><h3>🧠 Series Index</h3><p>1️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-1-from-cpu-cores-to-mach-threads-and-thread-pools-d1ebd31ef138">Part 1 — From CPU Cores to Mach Threads</a></p><p>2️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-a-thread-safety-synchronisation-mechanics-42f9714b8cf2">Part 2(a) — Thread Safety &amp; Synchronisation</a></p><p>3️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-b-actors-isolation-in-swift-concurrency-ec2d567118dc">Part 2(b) — Actors &amp; Isolation in Swift Concurrency</a></p><p>4️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-c-debugging-concurrency-in-swift-b4f330b46460">Part 2(c) — Debugging Concurrency in Swift</a></p><p>5️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-3-a-foundations-of-grand-central-dispatch-gcd-43343a45dc11">Part 3(a) — Inside GCD (Foundations)</a></p><p>6️⃣ <strong>Part 3(b) — Practical Thread-Safety Patterns in GCD (You’re Here)</strong></p><p>7️⃣ Part 3(c) — GCD Under the Hood (Coming Soon)</p><p>Find this Helpful — Follow me on LinkedIn: <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01">www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99cfe665e386" width="1" height="1" alt=""><hr><p><a href="https://medium.com/master-ios-concurrency/concurrency-in-ios-part-3-b-practical-thread-safety-patterns-in-gcd-lld-insights-99cfe665e386">Concurrency in iOS — Part 3(b): Practical Thread-Safety Patterns in GCD + LLD Insights</a> was originally published in <a href="https://medium.com/master-ios-concurrency">Master iOS Concurrency</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency in iOS — Part 3(c): GCD Internals & Debugging Insights]]></title>
            <link>https://medium.com/master-ios-concurrency/concurrency-in-ios-part-3-c-gcd-internals-debugging-insights-778122a94fee?source=rss----c379d6f0cd70---4</link>
            <guid isPermaLink="false">https://medium.com/p/778122a94fee</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Anubhav Giri]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 06:12:47 GMT</pubDate>
            <atom:updated>2026-06-12T06:12:48.675Z</atom:updated>
            <content:encoded><![CDATA[<h3>Concurrency in iOS — Part 3(c): GCD Internals &amp; Debugging Insights</h3><blockquote><em>“To truly understand concurrency, look beneath the queues.”</em></blockquote><h3>📘 TL;DR</h3><p>This part dives under the hood of <strong>Grand Central Dispatch (GCD)</strong> — exploring how Apple’s concurrency engine actually works, how to debug it, and how to prevent common production issues.</p><p><strong>Key takeaways:</strong></p><ul><li>Understand GCD’s <strong>thread pool and scheduling</strong>.</li><li>Use <strong>barriers</strong> only on custom queues.</li><li>Specify <strong>QoS</strong> explicitly to avoid UI lag.</li><li>Apply <strong>preconditions</strong> safely in production.</li><li>Trust GCD’s <strong>built-in memory barriers</strong> for correctness.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*hw2TL5lYZNRQ9PsAk8qkLA.png" /></figure><h3>1. Inside the GCD Engine</h3><p>At runtime, every DispatchQueue you create is powered by <strong>libdispatch</strong> — Apple’s low-level concurrency runtime built atop <strong>Darwin (XNU)</strong> and <strong>Mach threads</strong>.</p><pre>Swift Code → libdispatch (GCD runtime)<br>              ↓<br>          Darwin pthreads / Mach threads<br>              ↓<br>          XNU Kernel Scheduler → CPU Cores</pre><p>🧩 <strong>Think of it like this:</strong><br>- Swift gives you the dashboard (DispatchQueue),<br>- GCD is the engine (libdispatch),<br>- and the kernel scheduler is the driver that assigns threads to CPU cores.</p><h3>How Threads Are Managed</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Vb_59DsWYlxO7r-2BHodA.png" /></figure><p>💡 <strong>Analogy:</strong> GCD is a <em>smart traffic controller</em> — it routes your async work to the most efficient lane without letting the highway jam.</p><h3>🧭 GCD Architecture Diagram</h3><pre>                    ┌──────────────────────────────┐<br>                    │         Swift Code           │<br>                    │   (DispatchQueue / async)    │<br>                    └──────────────┬───────────────┘<br>                                   │<br>                                   ▼<br>                    ┌──────────────────────────────┐<br>                    │        libdispatch           │<br>                    │   (Work queues, barriers,    │<br>                    │    thread pool, QoS)         │<br>                    └──────────────┬───────────────┘<br>                                   │<br>                                   ▼<br>                    ┌──────────────────────────────┐<br>                    │    Mach Threads / Kernel     │<br>                    │   (Scheduler → CPU cores)    │<br>                    └──────────────────────────────┘</pre><h3>2. Target Queues &amp; Hierarchy</h3><p>Target queues help you control concurrency and QoS across multiple queues that work together.</p><pre>let parent = DispatchQueue(label: &quot;com.app.db&quot;,<br>                           qos: .utility,<br>                           attributes: .concurrent)<br><br>let reads  = DispatchQueue(label: &quot;com.app.db.reads&quot;, target: parent)<br><br>let writes = DispatchQueue(label: &quot;com.app.db.writes&quot;, target: parent)</pre><h3>✅ Benefits</h3><ul><li>Shared thread pool → prevents oversubscription</li><li>Unified QoS control at parent level</li><li>Testing flexibility → redirect all DB work to .main</li><li>Ordered access without losing concurrency</li></ul><p>💡 Great for architectures like <strong>read–write segregation</strong> in database or cache modules.</p><h3>3. Reader–Writer Barrier Pattern</h3><p>Barriers implement a <strong>readers–writer lock</strong> under the hood: many reads in parallel, writes one at a time.</p><pre>final class ConcurrentCache {<br>    private let queue = DispatchQueue(label: &quot;cache&quot;,<br>                                      attributes: .concurrent)<br>    private var storage: [String: Data] = [:]<br>    <br>    func getSync(_ key: String) -&gt; Data? {<br>        queue.sync {<br>            storage[key]<br>        }<br>    }<br>    <br>    func getAsync(_ key: String, completion: @escaping (Data?) -&gt; Void) {<br>        queue.async {<br>            completion(self.storage[key])<br>        }<br>    }<br>    <br>    func set(_ data: Data, for key: String) {<br>        queue.async(flags: .barrier) {<br>            self.storage[key] = data<br>        }<br>    }<br>}</pre><h3>🧩 Choosing Between Approaches</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tzV-cPeMzWnbqzFV-icDNg.png" /></figure><p>*Both are thread-safe and see committed writes — the only difference is <em>when</em> the read executes, not <em>what</em> it sees.</p><h3>4. Memory Barriers &amp; Visibility</h3><p>Every .sync or .barrier introduces a <strong>hardware memory barrier</strong>, ensuring cache coherence across CPU cores.</p><pre>queue.async(flags: .barrier) {<br>    sharedBuffer.flush() // all prior writes visible before this executes<br>}</pre><p>Establishes a “happens-before” relationship between reads and writes.</p><p>⚠️ You rarely need to think about this directly in Swift — GCD handles it.<br>Only relevant when:</p><ul><li>Interfacing with C/C++ concurrent code</li><li>Using Swift Atomics</li><li>Debugging at the assembly level</li></ul><h3>5. Thread Pool Behavior</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CuRFMGWjHr7zaklQWt3tHQ.png" /></figure><p>💡 Avoid Thread.sleep() in production. Use asyncAfter or non-blocking APIs.</p><h3>6. Dispatch Preconditions</h3><p>Validate queue context at runtime — critical for data integrity.</p><h3>✅ During Development</h3><p>Use liberally to catch off-queue calls.</p><h3>✅ In Production (Selectively)</h3><p>Crash early for critical invariants instead of risking corruption.</p><pre>final class DatabaseManager {<br>    private let dbQueue = DispatchQueue(label: &quot;db&quot;)<br><br>    private func _unsafeWrite(_ data: Data) {<br>        dispatchPrecondition(condition: .onQueue(dbQueue))<br>        database.write(data)<br>    }<br>}</pre><p><strong>Use for:</strong></p><ul><li>Database writes</li><li>Payment flows</li><li>Security-critical operations</li></ul><h3>❌ Avoid for Hot Paths</h3><p>Use assert(Thread.isMainThread) instead inside tight loops or UI work.</p><h3>7. Debugging GCD</h3><h3>🔍 Thread Sanitizer (TSan)</h3><p>Enable in <strong>Scheme → Diagnostics</strong> to detect data races.</p><h3>🧭 Instruments → System Trace</h3><p>Visualize queue activity, blocking syncs, and QoS shifts.</p><h3>🪄 Debug Cheatsheet</h3><pre>print(queue.label)<br>dispatchPrecondition(condition: .onQueue(queue))<br>print(&quot;Thread:&quot;, Thread.current)<br><br># LLDB<br>(lldb) po queue<br>(lldb) thread info<br>(lldb) bt   # backtrace to inspect nested sync calls</pre><h3>8. QoS Inheritance &amp; Promotion</h3><h3>🧩 QoS Inheritance — Common Bug</h3><pre>DispatchQueue.global(qos: .background).async {<br>    let data = fetchData()<br><br>    DispatchQueue.main.async {<br>        self.updateUI(data) // ⚠️ inherits background QoS → laggy UI<br>    }<br>}<br><br><br>// ✅ Fix<br>DispatchQueue.global(qos: .background).async {<br>    let data = fetchData()<br><br>    DispatchQueue.main.async(qos: .userInteractive) {<br>        self.updateUI(data)<br>    }<br>}</pre><p>💡 <strong>Production pitfall:</strong> Always override QoS for UI callbacks spawned from background work.</p><h3>QoS Promotion</h3><p>If high-priority work waits on a low-priority task (e.g. lock contention), GCD temporarily boosts the low-QoS task to prevent blocking.</p><h3>QoS Quick Reference</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrvcEOXqKuWnPzqYhZ6M5A.png" /></figure><h3>9. Playground Demo — Thread Reuse</h3><pre>import Foundation<br>import PlaygroundSupport<br><br>let queue = DispatchQueue(label: &quot;demo.concurrent&quot;, attributes: .concurrent)<br>let group = DispatchGroup()<br><br>for i in 1...5 {<br>    group.enter()<br>    queue.async {<br>        let thread = Thread.current<br>        print(&quot;⚙️ Task \(i) on thread \(thread)&quot;)<br>        // Using sleep to show thread reuse (avoid in production)<br>        Thread.sleep(forTimeInterval: 0.5)<br>        print(&quot;✅ Task \(i) finished on \(thread)&quot;)<br>        group.leave()<br>    }<br>}<br><br>group.notify(queue: .main) {<br>    print(&quot;🎉 All tasks complete on \(Thread.current)&quot;)<br>    PlaygroundPage.current.finishExecution()<br>}<br><br>PlaygroundPage.current.needsIndefiniteExecution = true</pre><p>💡 You’ll see threads being reused across tasks — a live demonstration of GCD’s thread-pool efficiency.</p><h3>10. concurrentPerform Best Practices</h3><pre>DispatchQueue.concurrentPerform(iterations: 500) { i in<br>    heavyComputation(i)<br>}</pre><p>✅ Use when:</p><ul><li>10–15 + iterations (minimum to offset overhead)</li><li>CPU-bound work &gt; 1 ms</li><li>Off main thread</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eX38ROUSqZaPXrFuqxzQAg.png" /></figure><h3>11. Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cw-_jFmnEyS5DNLI-7Kdsg.png" /></figure><h3>Top 5 GCD Mistakes (with Fixes)</h3><p>1️⃣ Barriers on global queues → ignored<br>2️⃣ Nested sync → deadlock<br>3️⃣ concurrentPerform on main → UI freeze<br>4️⃣ QoS inheritance → sluggish UI<br>5️⃣ Over-using sync → blocked threads</p><p>✅ Fix with: custom queues, async patterns, explicit QoS.</p><h3>Quick Decision Matrix</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CBuxEIDCqK3sgom2kuOmiQ.png" /></figure><h3>🧩 Series Continuation</h3><p>1️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-1-from-cpu-cores-to-mach-threads-and-thread-pools-d1ebd31ef138">Part 1 — From CPU Cores to Mach Threads</a><br>2️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-a-thread-safety-synchronisation-mechanics-42f9714b8cf2">Part 2(a) — Thread Safety &amp; Synchronisation</a><br>3️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-b-actors-isolation-in-swift-concurrency-ec2d567118dc">Part 2(b) — Actors &amp; Isolation in Swift Concurrency</a><br>4️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-c-debugging-concurrency-in-swift-b4f330b46460">Part 2(c) — Debugging Concurrency in Swift</a><br>5️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-3-a-foundations-of-grand-central-dispatch-gcd-43343a45dc11">Part 3(a) — Inside GCD (Foundations)</a><br>6️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-3-b-practical-thread-safety-patterns-in-gcd-lld-insights-99cfe665e386">Part 3(b) — Practical Thread-Safety Patterns (GCD + LLD)</a><br>7️⃣ <strong>Part 3(c) — GCD Internals &amp; Debugging Insights (You’re Here)</strong><br>8️⃣ Part 4 — Swift Concurrency: async/await &amp; Structured Concurrency <strong>(Coming Soon)</strong></p><h3>🎓 Key Takeaways</h3><p>✅ GCD manages threads efficiently with work-stealing<br>✅ Use barriers only on custom queues<br>✅ Specify QoS explicitly for UI callbacks<br>✅ Preconditions are safe for critical paths<br>✅ Memory barriers are automatic in GCD<br>✅ concurrentPerform = CPU-bound only<br>✅ Avoid nested sync and global barriers</p><p>🔥 You’ve officially mastered <strong>how GCD actually works under the hood</strong>.<br>Up next → <strong>Part 4:</strong> <em>async/await &amp; Structured Concurrency — where Swift’s modern concurrency meets GCD’s foundations.</em></p><p>Find this Helpful — Follow me on LinkedIn: <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01">www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=778122a94fee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/master-ios-concurrency/concurrency-in-ios-part-3-c-gcd-internals-debugging-insights-778122a94fee">Concurrency in iOS — Part 3(c): GCD Internals &amp; Debugging Insights</a> was originally published in <a href="https://medium.com/master-ios-concurrency">Master iOS Concurrency</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency in iOS — Part 1: From CPU Cores to Mach Threads and Thread Pools]]></title>
            <link>https://medium.com/master-ios-concurrency/concurrency-in-ios-part-1-from-cpu-cores-to-mach-threads-and-thread-pools-d1ebd31ef138?source=rss----c379d6f0cd70---4</link>
            <guid isPermaLink="false">https://medium.com/p/d1ebd31ef138</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Anubhav Giri]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 03:18:34 GMT</pubDate>
            <atom:updated>2026-06-12T03:18:35.421Z</atom:updated>
            <content:encoded><![CDATA[<h3>Concurrency in iOS — Part 1: From CPU Cores to Mach Threads and Thread Pools</h3><p><em>“Mastering iOS Concurrency, one byte at a time.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*-hbOsBSXC3kAskjA823eHw.png" /></figure><h3>Understanding the journey from DispatchQueue.async { } to silicon</h3><blockquote><em>“Every </em><em>DispatchQueue.async {} you write travels all the way down to the Darwin kernel — where Mach threads meet BSD processes.”</em></blockquote><p>Concurrency is one of the most crucial yet least understood areas of iOS development.<br>We use DispatchQueue, OperationQueue, or Swift Concurrency (async/await) every day — but few of us explore what happens <em>beneath</em> those APIs, where CPU cores, processes, threads, queues, and the Darwin kernel coordinate to keep your app smooth and battery-friendly.</p><p>Let’s peel that onion from silicon to Swift 👇</p><h3>1. Concurrency vs Parallelism — The Foundation</h3><p>Before diving deep, let’s clarify two concepts that developers often confuse:</p><p><strong>Concurrency</strong> → structuring your app so multiple tasks make progress together.<br><strong>Parallelism</strong> → multiple tasks run simultaneously on different cores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42FjtqFBwfgmZB9ru6Jl-A.png" /></figure><p><strong>Concurrency = software design</strong><br><strong>Parallelism = hardware execution</strong></p><p>You can have concurrency without parallelism (one core, multiple threads) — but not vice versa.</p><h3>2. CPU Cores — The Hardware Executors</h3><p>Modern iPhones use <strong>heterogeneous (big.LITTLE)</strong> CPU designs — a mix of powerful and efficient cores working together.</p><h3>Core Architecture in Recent iPhones</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sDEZoQ0l5lJ5K6CksCuBHQ.png" /></figure><p><em>(Example: A17 Pro = 2 P + 4 E cores)</em></p><p>Each Apple Silicon core executes <strong>one hardware thread</strong> — no SMT/Hyper-Threading.<br>The <strong>Mach scheduler</strong> dynamically assigns threads → cores based on QoS, thermal load, power state, and system load.</p><h3>💡 Does the Main Queue Run on a Performance or Efficiency Core?</h3><p>The <strong>main queue runs on the main thread</strong>, which normally sits on a <strong>Performance core</strong> while your app is active or rendering UI — ensuring smooth animations and responsiveness.</p><p>However, the Mach scheduler can migrate it to an <strong>Efficiency core</strong> during:</p><ul><li>Low Power Mode</li><li>Idle UI / background execution</li><li>Thermal throttling or system load balancing</li></ul><blockquote><em>🧩 Main queue → </em><strong><em>Performance core by default</em></strong><em><br>💤 May shift to </em><strong><em>Efficiency core</em></strong><em> under low-power conditions</em></blockquote><p>This migration is fully <strong>transparent</strong> — there’s no API to bind threads to specific cores.</p><h3>3. Darwin Kernel — Where Mach Meets BSD</h3><p>Darwin (the foundation of iOS &amp; macOS) is built on <strong>XNU</strong>, a hybrid kernel combining:</p><h3>Mach Microkernel</h3><ul><li>Tasks &amp; Threads → core scheduling primitives</li><li>Scheduling &amp; QoS priorities</li><li>Virtual memory management</li><li>IPC via Mach ports</li></ul><h3>BSD Subsystem</h3><ul><li>Processes &amp; POSIX APIs (fork, sockets, pthread)</li><li>File system &amp; network stack</li><li>Permissions &amp; signals</li><li>System calls + UNIX compatibility</li></ul><h3>Relationship</h3><p>Every <strong>BSD process = one Mach task</strong>, which owns multiple Mach threads:</p><pre>BSD Process (App)<br> │<br> └── Mach Task<br>      ├─ Mach Thread 1 (Main)<br>      ├─ Mach Thread 2<br>      └─ Mach Thread 3 → scheduled on CPU cores</pre><p>This hybrid design delivers Mach’s modularity + BSD’s performance.</p><h3>4. Process in iOS — Your App’s Sandbox</h3><p>When you tap your app icon:</p><p>1️⃣ SpringBoard asks launchd to spawn a process<br>2️⃣ Kernel creates a Mach task + first thread<br>3️⃣ That thread runs main() → UIKit / SwiftUI bootstraps<br>4️⃣ @main entry point executes → run loop starts</p><h3>How Many Processes Per App?</h3><ul><li><strong>Normal:</strong> 1 process per app</li><li><strong>Extensions:</strong> Each runs in its own sandboxed process (Share, Widget, App Clip, etc.)</li></ul><p>Each process gets:</p><ul><li>Isolated virtual memory</li><li>Own file descriptors &amp; resources</li><li>Independent sandbox protection</li></ul><h3>5. Threads — The Execution Units</h3><p>Threads are the actual workers executed by CPU cores.</p><p>Each thread has its own stack and registers but shares process memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jvsnx-0_RsS1vrOWj9iuGg.png" /></figure><p><strong>Typical thread counts:</strong></p><ul><li>Idle: 5–15</li><li>Medium activity: 20–40</li><li>Heavy load: 80–150 ⚠️ (“thread explosion”)</li></ul><blockquote><em>80 + threads usually signal blocking on concurrent queues or run-away tasks — not true concurrency.</em></blockquote><h3>6. Queues — Abstraction Over Threads</h3><p>A DispatchQueue (GCD) is a <strong>FIFO queue</strong> executed by a shared thread pool.<br>You enqueue work; the system decides which thread runs it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WGxZHsX34fFfmJiczkhpiA.png" /></figure><p>🧩 System provides <strong>1 Main + 4 Global concurrent queues</strong>.<br>Custom queues share the same underlying thread pools.</p><h3>7. Thread Pools — Efficient Thread Reuse</h3><blockquote><em>“Creating threads is expensive; reusing them is concurrency done right.”</em></blockquote><p>A <strong>thread pool</strong> is a set of pre-created threads ready to run tasks.<br>Instead of spawning new threads for every task, threads are reused.</p><h3>Why They Exist</h3><ul><li>Creation ≈ 100–200 µs + stack allocation</li><li>Context switch overhead (1–5 µs)</li><li>Battery &amp; thermal impact of many idle threads</li></ul><h3>Lifecycle</h3><pre>Task Queue<br> ↓<br>Thread Pool (per QoS)<br> ↓<br>Idle Thread → Executes Task → Sleeps</pre><h3>GCD Pools</h3><ul><li>Adaptive size per QoS level</li><li>Can grow 20–60 threads under load</li><li>Can shrink when idle</li></ul><p>⚠️ <strong>Thread Explosion:</strong> Blocking work on concurrent queues causes new threads to spawn → context switch storms.</p><h3>OperationQueue</h3><pre>let queue = OperationQueue()<br>queue.maxConcurrentOperationCount = 4</pre><p>Capped pool per queue — prevents run-away threads.</p><h3>Swift Concurrency (Thread Model 2021 +)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*svmG_YldzDkTcLYpib7qkQ.png" /></figure><pre>Task {<br>    let data = await fetchData()     // Thread freed here<br>    await process(data)              // May resume elsewhere<br>}</pre><p>Thousands of Tasks → a handful of threads.</p><h3>8. Context Switching — When Threads Take Turns</h3><p>Each switch saves current registers + stack pointer, loads the next thread, and flushes caches.</p><p><strong>Cost:</strong> 1–5 µs each → thousands per second = lost performance.<br>Fewer threads doing more work beats many threads mostly waiting.</p><h3>9. From Swift to Silicon — The Journey</h3><pre>Swift Task / Closure<br> ↓<br>Swift Runtime / DispatchQueue<br> ↓<br>Thread Pool (per QoS)<br> ↓<br>Mach Threads<br> ↓<br>Darwin Scheduler<br> ↓<br>CPU Cores (P / E)<br> ↓<br>Silicon Execution</pre><p>Every async call travels this path — from your Swift code to actual electrons switching on Apple Silicon.</p><h3>10. Layer Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Quz4reTpwfXYH2V2N9Gw-A.png" /></figure><h3>11. Key Takeaways</h3><p>✅ Main Queue → Performance core by default; migrates when idle<br>✅ 1 BSD process = 1 Mach task per app<br>✅ Mach threads scheduled across P/E cores by QoS<br>✅ Apple Silicon → 1 thread per core (no SMT)<br>✅ Thread pools reuse threads → lower overhead<br>✅ GCD can over-spawn threads; Swift Concurrency cannot<br>✅ Context switch ≈ 1–5 µs → avoid thread explosion</p><h3>12. Practical Tips</h3><p><strong>✅ Do this</strong></p><ul><li>Use Task / async await for new code</li><li>Use QoS wisely for prioritization</li><li>Keep main thread non-blocking</li><li>Profile with Instruments → <strong>Thread States</strong>, <strong>Time Profiler</strong></li><li>Let the system decide thread count</li></ul><p><strong>❌ Avoid</strong></p><ul><li>Manual Thread() / pthread_create()</li><li>Blocking calls on concurrent queues</li><li>Synchronous network operations</li><li>Heavy work on .userInteractive queues</li><li>Assuming “more threads = faster”</li></ul><h3>🚀 Next in the Series → Part 2 — Thread Safety &amp; Race Conditions</h3><p>We’ll explore:</p><ul><li>How race conditions corrupt memory</li><li>Locks, semaphores, barriers, atomics</li><li>Swift Actors &amp; isolation</li><li>Cache coherency + memory ordering</li></ul><h3>🎓 Further Reading</h3><p><strong>WWDC Sessions</strong></p><ul><li><em>Swift Concurrency: Behind the Scenes</em> (2021)</li><li><em>Protect Mutable State with Swift Actors</em> (2021)</li><li><em>Eliminate Data Races Using Swift Concurrency</em> (2022)</li></ul><p><strong>Docs &amp; Source</strong></p><ul><li><a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/">Concurrency Programming Guide</a></li><li><a href="https://developer.apple.com/documentation/dispatch">Dispatch Framework</a></li><li><a href="https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html">Swift Concurrency Guide</a></li><li><a href="https://github.com/apple/darwin-xnu">XNU Kernel Source</a></li><li><a href="https://github.com/apple/swift-corelibs-libdispatch">libdispatch Source</a></li></ul><h3>💬 Closing Thoughts</h3><p>Understanding concurrency from CPU cores to Swift syntax isn’t just academic — it makes you a sharper iOS engineer.<br>You’ll design smoother UIs, diagnose threading bugs faster, and architect systems that scale with Apple Silicon.</p><p>The next time you write DispatchQueue.async {} or Task {}, remember:<br>your closure travels from Swift’s friendly syntax down through Darwin’s kernel to the very core of the A-series chip.</p><p>Never look at async the same way again 🚀</p><p><em>Found this helpful? Follow for Part 2 on Thread Safety and Race Conditions!</em><br><em>Comments and discussions welcome below 👇</em></p><p>Follow me on LinkedIn: <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01">www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1ebd31ef138" width="1" height="1" alt=""><hr><p><a href="https://medium.com/master-ios-concurrency/concurrency-in-ios-part-1-from-cpu-cores-to-mach-threads-and-thread-pools-d1ebd31ef138">Concurrency in iOS — Part 1: From CPU Cores to Mach Threads and Thread Pools</a> was originally published in <a href="https://medium.com/master-ios-concurrency">Master iOS Concurrency</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency in iOS — Part 4: async/await & Structured Concurrency]]></title>
            <link>https://medium.com/master-ios-concurrency/concurrency-in-ios-part-4-async-await-structured-concurrency-7486fa303aeb?source=rss----c379d6f0cd70---4</link>
            <guid isPermaLink="false">https://medium.com/p/7486fa303aeb</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Anubhav Giri]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 03:18:09 GMT</pubDate>
            <atom:updated>2026-06-12T03:18:10.506Z</atom:updated>
            <content:encoded><![CDATA[<h3>Concurrency in iOS — Part 4: async/await &amp; Structured Concurrency</h3><blockquote><em>“If GCD is the engine, Swift Concurrency is the autopilot.”</em></blockquote><h3>📘 TL;DR</h3><p>Swift Concurrency replaces callback hell with safe, structured async code.<br>You’ll learn how async/await, actors, continuations, and async sequences work under the hood—and how they differ from GCD.<br>We’ll correct common myths, explain reentrancy, TaskLocal context, and show production-safe patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*A3t_7SpCYN2gkUcMuuSb9A.png" /></figure><h3>1 · From GCD to Swift Concurrency</h3><p>Before Swift 5.5:</p><pre>// Before Swift 5.5 - &quot;Callback Pyramid&quot; / &quot;Callback Hell&quot;<br>fetchUser { user in<br>    fetchPosts(for: user) { posts in<br>        fetchComments(for: posts) { comments in<br>            updateUI(with: comments)<br>        }<br>    }<br>}</pre><p>Callback pyramids. No cancellation. Race risks.<br>Swift Concurrency introduced compiler-checked async tasks with structured lifetimes.</p><h3>2 · async/await — Cooperative Scheduling</h3><pre>func fetchUser() async -&gt; User { ... }<br>func fetchPosts(for user: User) async -&gt; [Post] { ... }<br><br>func showFeed() async {<br>    let user  = await fetchUser()<br>    let posts = await fetchPosts(for: user)<br>    print(&quot;✅ \(posts.count) posts loaded&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8R-sJK4XU-BsYpnHFN4sbA.png" /></figure><blockquote><em>await doesn’t enqueue to a queue — it </em><strong><em>yields</em></strong><em> to the cooperative pool.<br>The runtime keeps state machines alive and resumes them later, maybe on another thread.</em></blockquote><h3>3 · Structured Concurrency — Scoped and Safe</h3><pre>func loadDashboard() async {<br>    async let user  = fetchUser()<br>    async let posts = fetchPosts()<br>    let (u, p) = await (user, posts)<br>    updateUI(u, p)<br>}</pre><p>Child tasks are tied to the scope — cancelled automatically if the parent fails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XBK-zCQV1GihOR2cO-A9Sg.png" /></figure><h3>4 · TaskGroups + Cancellation</h3><pre>try await withThrowingTaskGroup(of: Data.self) { group in<br>    for id in ids {<br>        group.addTask { try await fetchData(id) }<br>    }<br><br>    for try await result in group {<br>        process(result)<br>        if Task.isCancelled { break }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5hsEz_8erN4rfTySnXkZA.png" /></figure><h3>5 · Task Priority — Quick Guide</h3><pre>Task(priority: .userInitiated) {<br>    await heavyComputation()<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qU7DJFTKhgTmLYhOOhktgg.png" /></figure><p>Tasks may auto-escalate if a higher-priority task awaits them.</p><h3>🧠 6 · Actors — Isolation ≠ Serialization</h3><pre>actor BankAccount {<br>    var balance = 100<br>    <br>    func withdraw(_ amount: Int) async {<br>        guard balance &gt;= amount else { <br>          return <br>        }<br><br>        await Task.sleep(1_000_000_000) // Suspends<br><br>        balance -= amount // ⚠️ State may have changed<br>    }<br>}</pre><p>Actors serialize access only <strong>between awaits</strong>.<br>State can change after suspension → <strong>reentrancy</strong>.</p><p>✅ <strong>Fix: capture state before await</strong></p><pre>actor BankAccount {<br>    var balance = 100<br>    <br>    func withdraw(_ amount: Int) async {<br>        guard balance &gt;= amount else { return }<br>        await Task.sleep(1_000_000_000)  // ⚠️ Suspension point<br>        balance -= amount  // Unsafe: state may have changed<br>    }<br>    <br>    // ✅ Fix 1: Modify before suspension<br>    func safeWithdraw(_ amount: Int) async {<br>        guard balance &gt;= amount else { return }<br>        balance -= amount  // Update immediately<br>        await Task.sleep(1_000_000_000)<br>    }<br>    <br>    // ✅ Fix 2: No suspension = no reentrancy<br>    func withdrawSync(_ amount: Int) {<br>        guard balance &gt;= amount else { return }<br>        balance -= amount<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O6nj4mtxaTZpPTR0mfeYTw.png" /></figure><h3>🧱 7 · Sendable — Safe Across Boundaries</h3><pre>struct Profile: Sendable {<br>    let name: String<br>    let age: Int<br>}<br><br>// ⚠️ @unchecked Sendable requires manual synchronization<br>final class Cache: @unchecked Sendable {<br>    private let lock = NSLock()<br>    private var data: [String: Data] = [:]<br>    <br>    func get(_ key: String) -&gt; Data? {<br>        lock.lock()<br>        defer {<br>            lock.unlock()<br>        }<br>        return data[key]<br>    }<br>    <br>    func set(_ key: String, value: Data) {<br>        lock.lock()<br>        defer {<br>            lock.unlock()<br>        }<br>        data[key] = value<br>    }<br>}</pre><p>⚠️ @unchecked Sendable bypasses compiler safety—use only with manual locking or atomics.</p><h3>🔄 8 · Continuations — Bridge Old APIs</h3><pre>func loadImage(from url: URL) async throws -&gt; UIImage {<br>    try await withCheckedThrowingContinuation { continuation in<br>        URLSession.shared.dataTask(with: url) { data, _, error in<br>            if let error = error {<br>                continuation.resume(throwing: error)<br>            } else if let data = data, let image = UIImage(data: data) {<br>                continuation.resume(returning: image)<br>            } else {<br>                continuation.resume(throwing: URLError(.badServerResponse))<br>            }<br>        }.resume()<br>    }<br>}</pre><p>⚠️ Call resume() <strong>exactly once,</strong> twice = crash, never = hang.</p><h3>🧵 9 · AsyncSequence — Streams with Cancellation</h3><pre>// Timer-based stream with proper cleanup<br>let stream = AsyncStream(Int.self) { continuation in<br>    let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in<br>        continuation.yield(Int.random(in: 0..&lt;10))<br>    }<br>    continuation.onTermination = { @Sendable _ in<br>        timer.invalidate()<br>    }<br>}</pre><p>Custom network stream:</p><pre>// Custom network stream<br>struct NetworkStream: AsyncSequence {<br>    typealias Element = Data<br>    let url: URL<br>    <br>    func makeAsyncIterator() -&gt; Iterator {<br>        Iterator(url: url)<br>    }<br>    <br>    struct Iterator: AsyncIteratorProtocol {<br>        let url: URL<br>        var offset = 0<br>        <br>        mutating func next() async throws -&gt; Data? {<br>            try Task.checkCancellation()<br>            <br>            var request = URLRequest(url: url)<br>            request.setValue(&quot;bytes=\(offset)-\(offset + 4095)&quot;, <br>                           forHTTPHeaderField: &quot;Range&quot;)<br>            <br>            let (data, _) = try await URLSession.shared.data(for: request)<br>            guard !data.isEmpty else { return nil }<br>            <br>            offset += data.count<br>            return data<br>        }<br>    }<br>}</pre><h3>10 · TaskLocal Values — Scoped Context</h3><pre>enum UserContext {<br>    @TaskLocal static var userID: String?<br>}<br><br><br>UserContext.$userID.withValue(&quot;user123&quot;) {<br>    await processRequest()<br>} // ✅ userID automatically restored after scope</pre><blockquote><em>💡 TaskLocal values are </em><strong><em>scoped</em></strong><em> and auto-restore after the block exits.</em></blockquote><h3>11 · MainActor — UI Safety Simplified</h3><pre>@MainActor<br>final class DashboardViewModel {<br>    func updateUI() {<br>        label.text = &quot;Updated safely&quot;<br>    }<br>}</pre><p>Compiler-managed UI hops — no manual DispatchQueue.main.async.</p><h3>12 · Under the Hood — GCD vs Swift Concurrency</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6TfTf9C9X_LdZbdqyV4-Q.png" /></figure><h3>13 · When Not to Use Swift Concurrency</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W72SKxfKjAK7HbyC_NXPwA.png" /></figure><h3>14 · Debugging Toolkit</h3><ul><li>✅ Thread Sanitizer</li><li>✅ Instruments → Concurrency Template</li><li>✅ Task.isCancelled loops</li><li>✅ TaskLocal trace IDs</li><li>✅ Async backtraces (Xcode 15+)</li></ul><h3>15 · Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZxFJho1WGmx4U8txN_eZrg.png" /></figure><h3>🎓 Key Takeaways</h3><p>✅ Swift Concurrency = cooperative structured parallelism<br>✅ Actors ≠ queues; they’re executor-isolated<br>✅ AsyncSequence and TaskLocal add contextual power<br>✅ Continuations bridge legacy callbacks safely (once!)<br>✅ Task priorities already influence scheduling<br>✅ GCD still wins for deterministic low-level control</p><h3>🔜 Next in the Series</h3><p><strong>Part 5 — Advanced Swift Concurrency: Executors, Priorities &amp; Performance Tuning</strong><br>We’ll explore how Swift’s cooperative scheduler manages threads, custom executors, and real-world performance tuning.</p><p>Find this Helpful — Follow me on LinkedIn: <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01">www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7486fa303aeb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/master-ios-concurrency/concurrency-in-ios-part-4-async-await-structured-concurrency-7486fa303aeb">Concurrency in iOS — Part 4: async/await &amp; Structured Concurrency</a> was originally published in <a href="https://medium.com/master-ios-concurrency">Master iOS Concurrency</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency in iOS — Part 5(a): Actors & Executors — The Swift Concurrency Engine]]></title>
            <link>https://medium.com/master-ios-concurrency/concurrency-in-ios-part-5-a-actors-executors-the-swift-concurrency-engine-1b3e46d20def?source=rss----c379d6f0cd70---4</link>
            <guid isPermaLink="false">https://medium.com/p/1b3e46d20def</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Anubhav Giri]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 03:17:44 GMT</pubDate>
            <atom:updated>2026-06-12T03:17:45.950Z</atom:updated>
            <content:encoded><![CDATA[<h3>Concurrency in iOS — Part 5(a): Actors &amp; Executors — The Swift Concurrency Engine</h3><blockquote><em>“If async/await is the language, Executors are the runtime heartbeat that makes it possible.”</em></blockquote><h3>🚀 TL;DR — Understanding the Engine Before the Patterns</h3><p>In this part, we open the hood of <strong>Swift Concurrency</strong> — understanding how tasks, actors, and executors cooperate on a <strong>lightweight, cooperative thread pool</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*NzqpsQKoJM2Goho46gjQ1g.png" /></figure><p>You’ll learn:</p><ul><li>How async/await becomes a Task at runtime.</li><li>Why actors aren’t queues but <strong>isolated executors</strong>.</li><li>How Swift avoids blocking threads while ensuring thread safety.</li><li>What reentrancy means (and how to avoid subtle data bugs).</li><li>How executor hopping lets you jump back to the main thread cleanly.</li></ul><p>📌 <strong>In Part 5(b)</strong> we’ll build on this foundation with real-world patterns:<br>Continuations, TaskLocal, Sendable, AsyncSequence, structured concurrency — and when to use GCD instead.</p><h3>1. From async/await → Tasks</h3><p><em>What happens at compile time.</em></p><p>When you call an async function:</p><pre>func fetchUser() async -&gt; User {<br>    try await Task.sleep(nanoseconds: 1_000_000_000)<br>    return User(id: 42, name: &quot;Swift&quot;)<br>}</pre><p>…the compiler secretly builds a <strong>Task</strong> object that records its state and suspension points:</p><pre>Task {<br>    let user = await fetchUser()<br>    print(user)<br>}<br><br>await → suspension point  <br>Task  → continuation captured  <br>Executor → schedules next runnable task  <br>Thread  → reused from cooperative pool</pre><p>When the task suspends, the thread is returned to the pool to serve other tasks.</p><h3>2. The Cooperative Thread Pool</h3><p><em>Why suspension doesn’t block.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fptBCbWB1QPQGkGUtCfpPA.png" /></figure><p>💡 <strong>Why this matters:</strong> with GCD, spawning 1000 queues can create 1000+ threads, thrashing the CPU.<br>With Swift Concurrency, 1000 tasks share ~8 threads (on an 8-core device), cooperating efficiently.</p><pre>try await Task.yield()  // voluntarily give up the thread</pre><h3>3. Actors — Isolation Without Locks</h3><p><em>Serial execution without mutexes.</em></p><pre>actor Counter {<br>    private var value = 0<br>    <br>    func increment() {<br>        value += 1<br>    }<br>    <br>    func current() -&gt; Int {<br>        value<br>    }<br>}</pre><p>Each actor owns a <strong>serial executor</strong> ensuring one call at a time — no locks needed, no race conditions.</p><h3>4. Actor Reentrancy — The Hidden Trap</h3><p>Reentrancy means another task can enter the actor while it’s suspended:</p><pre>actor BankAccount {<br>    var balance = 100<br>    <br>    func withdraw(_ amount: Int) async {<br>        guard balance &gt;= amount else { return }<br>        await Task.sleep(1_000_000_000)   // suspension!<br>        balance -= amount  // ❌ balance may have changed<br>    }<br>}</pre><h3>✅ Safe Pattern — Capture Before Suspend</h3><pre>actor BankAccount {<br>    var balance = 100<br>    <br>    func withdraw(_ amount: Int) async {<br>        guard balance &gt;= amount else { return }<br>        let newBalance = balance - amount   // capture<br>        await Task.sleep(1_000_000_000)<br>        balance = newBalance                // safe<br>    }<br>    <br>    func withdrawSync(_ amount: Int) {      // no await = no reentrancy<br>        guard balance &gt;= amount else { return }<br>        balance -= amount<br>    }<br>}</pre><p>💡 Capture all state you need <strong>before</strong> any await.</p><p>💡 <strong>Note on Scope</strong><br>This article focuses on the <strong>runtime engine</strong> — how tasks, actors, and executors work under the hood.</p><p><strong>Not covered here (coming in Part 5(b)):</strong></p><ul><li>Continuations (bridging callbacks)</li><li>TaskLocal (context propagation)</li><li>Sendable (thread-safety rules)</li><li>AsyncSequence (streaming patterns)</li><li>When to use GCD instead</li></ul><p>We’re building the foundation first, then the patterns.</p><h3>5. Executors — Who Runs the Work?</h3><p><em>How tasks and actors are scheduled.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQ6iRbEqZaz_9rpgdDzTPw.png" /></figure><h3>Example — Executor Hopping</h3><pre>@MainActor<br>func renderUI() {<br>    label.text = &quot;Loaded ✅&quot;<br>}<br><br>func loadData() async {<br>    let data = await fetchData()           // background<br>    <br>    await MainActor.run {<br>        renderUI()<br>    }     // hop to main thread<br>}</pre><p>Or let the compiler infer the hop:</p><pre>func loadData() async {<br>    let data = await fetchData()<br>    await updateUI(with: data)<br>}<br><br>@MainActor<br>func updateUI(with data: Data) { ... }</pre><h3>6. Task Priority &amp; Escalation</h3><p><em>How scheduling fairness works.</em></p><pre>Task(priority: .userInitiated) {<br>    await heavyComputation()<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wewh2zWOiF8XxQysHblN7A.png" /></figure><p>⚠️ <strong>Priority Inversion Example</strong></p><pre>Task(priority: .background) {<br>    await actor.lockResource()   // holds resource<br>}<br><br>Task(priority: .userInitiated) {<br>    await actor.accessResource() // blocked by background task<br>}</pre><p>The runtime detects this and may temporarily <strong>escalate</strong> the background task’s priority to unblock the high-priority one.</p><h3>🔁 7. Cooperation Between Tasks &amp; Executors</h3><p><em>How multiple tasks share the same actor executor efficiently.</em></p><pre>actor Database {<br>    func query(_ sql: String) async -&gt; [Row] { ... }<br>}<br><br>func fetchReports(db: Database) async {<br>    async let users = db.query(&quot;SELECT * FROM users&quot;)<br>    async let orders = db.query(&quot;SELECT * FROM orders&quot;)<br>    await (try? users, try? orders)<br>}</pre><p>Tasks run concurrently but serialize inside the actor. Swift’s cooperative pool reuses threads efficiently.</p><p>💡 <strong>Coming in Part 5(b):</strong> We’ll explore how to compose multiple concurrent operations using TaskGroup for structured concurrency and how to handle cancellation across task hierarchies.</p><h3>8. Runtime Flow Diagram</h3><pre>async/await<br>   ↓<br>Task → Continuation<br>   ↓<br>Executor (Actor / MainActor / Default)<br>   ↓<br>Cooperative Thread Pool<br>   ↓<br>Mach Threads → XNU Kernel → CPU Cores</pre><p>🧠 <strong>Mental Model Summary</strong></p><p>Think of Swift Concurrency as a restaurant kitchen:</p><p>🍳 <strong>Actors</strong> = Prep stations (one chef works there at a time)<br>👨‍🍳 <strong>Tasks</strong> = Orders (can pause while waiting for ingredients)<br>🏃 <strong>Executors</strong> = Kitchen manager (assigns chefs to stations)<br>🧑‍🍳 <strong>Thread Pool</strong> = Team of chefs (reused across many orders)<br>⏸️ <strong>await</strong> = “While I wait, go help someone else.”</p><p>Unlike a traditional kitchen where chefs wait idle (blocking threads),<br>Swift’s kitchen keeps everyone productive by reassigning work.</p><h3>🎯 Key Takeaways</h3><p>✅ Actors = Isolated executors, no locks<br>✅ await = suspension (point of cooperation, not blocking)<br>✅ Capture state before await → avoid reentrancy bugs<br>✅ Executors control where tasks run (MainActor = main thread)<br>✅ Thread pool is cooperative → lightweight and efficient<br>✅ Priorities guide scheduling but runtime may escalate</p><h3>🔜 What’s Next?</h3><p>You now understand the <strong>engine</strong> of Swift Concurrency.<br>In <strong>Part 5(b)</strong> we’ll master the <strong>patterns</strong>.</p><p>🔧 <strong>Practical Techniques</strong></p><ul><li>Bridge legacy callbacks with Continuations</li><li>Manage context with TaskLocal</li><li>Ensure safety with Sendable</li><li>Stream data with AsyncSequence</li><li>Compose work with Structured Concurrency</li></ul><p>📊 <strong>Decision Frameworks</strong></p><ul><li>When to use Swift Concurrency vs GCD</li><li>How to handle cancellation properly</li><li>Testing and debugging async code</li></ul><p>🎯 <strong>Plus:</strong> A complete quick-reference checklist of golden rules</p><p><strong>[Read Part 5(b) →]</strong> <em>(coming soon)</em></p><h3>📚 Series Index</h3><p>1️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-1-from-cpu-cores-to-mach-threads-and-thread-pools-d1ebd31ef138">Part 1: From CPU Cores to Mach Threads and Thread Pools</a><br>2️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-a-thread-safety-synchronisation-mechanics-42f9714b8cf2">Part 2(a): Thread Safety &amp; Synchronisation Mechanics</a><br>3️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-b-actors-isolation-in-swift-concurrency-ec2d567118dc">Part 2(b): Actors &amp; Isolation in Swift Concurrency</a><br>4️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-c-debugging-concurrency-in-swift-b4f330b46460">Part 2(c): Debugging Concurrency in Swift</a><br>5️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-3-a-foundations-of-grand-central-dispatch-gcd-43343a45dc11">Part 3(a): Foundations of Grand Central Dispatch (GCD)</a><br>6️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-3-b-practical-thread-safety-patterns-in-gcd-lld-insights-99cfe665e386">Part 3(b): Practical Thread-Safety Patterns in GCD + LLD Insights</a><br>7️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-3-c-gcd-internals-debugging-insights-778122a94fee">Part 3(c): GCD Internals &amp; Debugging Insights</a><br>8️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-4-async-await-structured-concurrency-7486fa303aeb">Part 4: async/await &amp; Structured Concurrency</a><br>9️⃣ <strong>Part 5(a) — Actors &amp; Executors (You’re Here)</strong><br>🔜 Part 5(b) — Swift Concurrency Patterns &amp; Best Practices</p><p>Find this Helpful —<a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01"> <strong>Follow me on LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b3e46d20def" width="1" height="1" alt=""><hr><p><a href="https://medium.com/master-ios-concurrency/concurrency-in-ios-part-5-a-actors-executors-the-swift-concurrency-engine-1b3e46d20def">Concurrency in iOS — Part 5(a): Actors &amp; Executors — The Swift Concurrency Engine</a> was originally published in <a href="https://medium.com/master-ios-concurrency">Master iOS Concurrency</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency in iOS — Part 5(b): Practical Swift Concurrency Patterns]]></title>
            <link>https://medium.com/master-ios-concurrency/concurrency-in-ios-part-5-b-practical-swift-concurrency-patterns-6a853aaed156?source=rss----c379d6f0cd70---4</link>
            <guid isPermaLink="false">https://medium.com/p/6a853aaed156</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Anubhav Giri]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 03:17:23 GMT</pubDate>
            <atom:updated>2026-06-12T03:17:24.544Z</atom:updated>
            <content:encoded><![CDATA[<h3>Concurrency in iOS — Part 5(b): Practical Swift Concurrency Patterns</h3><blockquote><em>“You understand the engine. Now let’s build something real.”</em></blockquote><p>In <strong>Part 5(a)</strong> we explored how <em>actors, tasks, and executors</em> form the Swift Concurrency engine — the invisible machinery behind async/await.<br>Now, in <strong>Part 5(b)</strong>, we shift from internals → <strong>to practical patterns</strong>: how you actually use these features in production-grade iOS apps.</p><h3>📋 TL;DR</h3><p>You’ll learn how to:</p><ul><li>Bridge legacy callbacks with <strong>Continuations</strong></li><li>Propagate context with <strong>TaskLocal</strong></li><li>Make shared types <strong>Sendable</strong> safely</li><li>Run parallel work with <strong>TaskGroup</strong></li><li>Handle <strong>Cancellation</strong> gracefully (and clean up)</li><li>Tune <strong>Task Priority</strong> for responsiveness</li></ul><h3>🧭 Pattern Selector (Quick Decision Flow)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*gqE8ynhzh3kSQrOLGD_byw.png" /></figure><p>📌 <strong>Next (Part 5(c))</strong>: <strong>AsyncSequence</strong> for live streams, <strong>Swift Concurrency vs GCD</strong> decision frameworks, and <strong>performance/testing</strong> patterns.</p><h3>1️⃣ Continuations — Bridging Legacy APIs</h3><p><strong>When to use:</strong> Migrating completion-based or delegate-style APIs to async/await without rewriting them.</p><pre>func loadUser() async throws -&gt; User {<br>    try await withCheckedThrowingContinuation { continuation in<br>        api.loadUser { result in<br>            switch result {<br>            case .success(let user):<br>                continuation.resume(returning: user)<br>            case .failure(let error):<br>                continuation.resume(throwing: error)<br>            }<br>        }<br>    }<br>}</pre><h3>⚙️ Rules</h3><ul><li>Call resume() <strong>exactly once</strong> — twice = crash, never = hang</li><li>Use <strong>withChecked…</strong> while building/debugging</li><li>Use <strong>withUnsafe…</strong> only when you’re sure (fewer checks, slightly faster)</li></ul><h3>❌ Common Mistake</h3><pre>// WRONG – can call resume twice<br>api.loadUser { result in<br>    if let user = result.user {<br>        continuation.resume(returning: user)<br>    }<br>    if let error = result.error {<br>        continuation.resume(throwing: error)   // ⚠️ crash<br>    }<br>}</pre><p><strong>Fix:</strong> Use exhaustive pattern matching (switch) so only one path resumes.</p><h3>✅ Defensive Continuation (cancellation + exactly-once)</h3><pre>func fetchData(_ url: URL) async throws -&gt; Data {<br>    try await withTaskCancellationHandler(operation: {<br>        try await withCheckedThrowingContinuation { continuation in<br>            // ensure exactly-once resume<br>            let once = ManagedAtomic&lt;Bool&gt;(false)<br>            let task = URLSession.shared.dataTask(with: url) { data, _, error in<br>                guard once.exchange(true, ordering: .acquiring) == false else { return }<br>                if let error = error {<br>                    continuation.resume(throwing: error)<br>                } else if let data = data {<br>                    continuation.resume(returning: data)<br>                } else {<br>                    continuation.resume(throwing: URLError(.badServerResponse))<br>                }<br>            }<br>            task.resume()<br><br>            // propagate Swift Task cancellation to legacy API<br>            Task {<br>                await Task.yield()<br>                if Task.isCancelled {<br>                    task.cancel()<br>                }<br>            }<br>        }<br>    }, onCancel: {<br>        // Optional: custom cleanup/logging on cancellation<br>        // e.g., invalidate tokens, release resources<br>    })<br>}</pre><blockquote><em>💡 Use case: Modernize legacy Core Bluetooth, </em><em>URLSession, or SDK callbacks </em>without<em> rewriting your API layer.</em></blockquote><h3>2️⃣ TaskLocal — Pass Context Without Parameters</h3><p>Sometimes you need lightweight metadata (e.g., userID, traceID) to flow through async calls <strong>without</strong> polluting every function signature.</p><pre>enum UserContext {<br>    @TaskLocal static var userID: String?<br>    @TaskLocal static var requestID: UUID?<br>}<br><br>// Set context for entire request scope<br>UserContext.$userID.withValue(&quot;user123&quot;) {<br>    UserContext.$requestID.withValue(UUID()) {<br>        await processRequest()<br>        await logActivity()   // Inherits both automatically ✅<br>    }<br>}<br><br>func logActivity() async {<br>    print(&quot;User:&quot;, UserContext.userID ?? &quot;unknown&quot;)<br>    print(&quot;Request:&quot;, UserContext.requestID?.uuidString ?? &quot;N/A&quot;)<br>}</pre><h3>📊 Common Use Cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gSBPr62LWuEHl-nw6lOAaQ.png" /></figure><p><strong>🔄 Auto-restore:</strong> When the closure ends, the previous context value is automatically restored — no leaks or manual cleanup.</p><h3>💡 Production Pattern: Actor + tracing</h3><pre>actor APIClient {<br>    @TaskLocal static var requestID: UUID?<br><br>    func makeRequest&lt;T: Decodable&gt;(_ endpoint: String) async throws -&gt; T {<br>        let id = UUID()<br>        return try await Self.$requestID.withValue(id) {<br>            logger.info(&quot;[\(id)] → \(endpoint)&quot;)<br>            defer { logger.info(&quot;[\(id)] ✓ \(endpoint)&quot;) }<br>            let data = try await fetchData(from: endpoint)<br>            return try JSONDecoder().decode(T.self, from: data)<br>        }<br>    }<br><br>    private func fetchData(from endpoint: String) async throws -&gt; Data {<br>        if let id = Self.requestID {<br>            logger.debug(&quot;[\(id)] fetching \(endpoint)&quot;)<br>        }<br>        // … perform network fetch<br>        return Data()<br>    }<br>}</pre><h3>3️⃣ Sendable — Safe Data Across Tasks</h3><p><strong>Sendable</strong> is a compiler contract ensuring data that crosses actor/task boundaries is safe.</p><h3>📒 Quick Reference</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UsEim-dez2pFnTDAunhd1g.png" /></figure><h4>✅ Value type example</h4><pre>struct Config: Sendable {<br>    let id: Int<br>    let name: String<br>    let settings: [String: String]<br>}</pre><h4>🧱 Reference type with explicit safety</h4><pre>final class DataManager: Sendable {<br>    private let queue = DispatchQueue(label: &quot;com.app.data&quot;)<br>    private var cache: [String: Data] = [:]   // Mutable state!<br><br>    func getData(for key: String) async -&gt; Data? {<br>        await withCheckedContinuation { continuation in<br>            queue.async {<br>                continuation.resume(returning: self.cache[key])<br>            }<br>        }<br>    }<br><br>    func setData(_ data: Data, for key: String) async {<br>        await withCheckedContinuation { continuation in<br>            queue.async {<br>                self.cache[key] = data<br>                continuation.resume(returning: ())<br>            }<br>        }<br>    }<br>}</pre><h4>⚠️ @unchecked Sendable (use sparingly)</h4><pre>final class LegacyCache: @unchecked Sendable {<br>    private var lock = NSLock()<br>    private var storage: [String: Any] = [:]<br><br>    func set(_ value: Any, for key: String) {<br>        lock.lock(); defer { lock.unlock() }<br>        storage[key] = value<br>    }<br><br>    func get(for key: String) -&gt; Any? {<br>        lock.lock(); defer { lock.unlock() }<br>        return storage[key]<br>    }<br>}</pre><p><strong>Golden rules:</strong></p><ul><li>Sendable isn’t “magic” — it’s a <strong>promise</strong> your type is cross-task safe.</li><li>If a type <strong>never</strong> crosses actor/task boundaries, it <strong>doesn’t need</strong> Sendable.</li></ul><h3>4️⃣ TaskGroup — Structured Parallelism</h3><p>Run multiple async operations concurrently, safely scoped and cancelable.</p><h3>🎯 Fail-Fast (default)</h3><pre>func loadDashboard() async throws -&gt; Dashboard {<br>    try await withThrowingTaskGroup(of: DashboardSection.self) { group in<br>        group.addTask { try await fetchUserProfile() }<br>        group.addTask { try await fetchNotifications() }<br>        group.addTask { try await fetchAnalytics() }<br><br>        var sections: [DashboardSection] = []<br><br>        for try await section in group {<br>            sections.append(section)<br>        }<br>        return Dashboard(sections: sections)<br>    }<br>}</pre><h3>📊 Error Handling Strategies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_-tl1Llb_PAV8zEKT84dg.png" /></figure><h4>💡 Collect-All (best effort)</h4><pre>func loadDashboardBestEffort() async -&gt; Dashboard {<br>    await withTaskGroup(of: Result&lt;DashboardSection, Error&gt;.self) { group in<br>        group.addTask { await Result { try await fetchUserProfile() } }<br>        group.addTask { await Result { try await fetchNotifications() } }<br>        group.addTask { await Result { try await fetchAnalytics() } }<br>        <br>        var sections: [DashboardSection] = []<br>        var errors: [Error] = []<br><br>        for await result in group {<br>            switch result {<br>            case .success(let section):<br>                sections.append(section)<br>            case .failure(let error):<br>                errors.append(error)<br>                logger.warning(&quot;Section failed: \(error)&quot;)<br>            }<br>        }<br>        return Dashboard(sections: sections, errors: errors)<br>    }<br>}</pre><h4>🎯 Example: Parallel image processing (ordered)</h4><pre>func processImages(_ urls: [URL]) async throws -&gt; [UIImage] {<br>    try await withThrowingTaskGroup(of: (Int, UIImage).self) { group in<br>        <br>        for (index, url) in urls.enumerated() {<br>            group.addTask {<br>                let (data, _) = try await URLSession.shared.data(from: url)<br>                guard let image = UIImage(data: data) else { throw ImageError.invalidData }<br>                return (index, image)<br>            }<br>        }<br>        var results: [(Int, UIImage)] = []<br>        <br>        for try await result in group { results.append(result) }<br>         <br>        return results.sorted { $0.0 &lt; $1.0 }.map { $0.1 }<br>    }<br>}</pre><h3>5️⃣ Cancellation — Graceful Exit</h3><p>Swift cancellation is <strong>cooperative</strong>: tasks must check and respect it.</p><h3>⚡ Throwing check (recommended)</h3><pre>func downloadLargeFile() async throws -&gt; Data {<br>    let handle = openFile()<br>    defer { handle.close() }            // Always cleanup<br><br>    var chunks: [Data] = []<br><br>    for i in 0..&lt;100 {<br>        try Task.checkCancellation()    // Throws CancellationError<br>        let chunk = try await downloadChunk(i)<br>        chunks.append(chunk)<br>    }<br>    return chunks.reduce(Data(), +)<br>}</pre><h3>🔇 Non-throwing check (graceful exit)</h3><pre>func processItems(_ items: [Item]) async {<br>    for item in items {<br>        guard !Task.isCancelled else {<br>            logger.info(&quot;Processing cancelled&quot;)<br>            break<br>        }<br>        await process(item)<br>    }<br>}</pre><h3>6️⃣ Task Priority — Controlling Scheduling</h3><pre>Task(priority: .userInitiated) {<br>    await fetchUserData()<br>}</pre><pre>Task(priority: .background) {<br>    await syncDatabase()<br>}</pre><h3>📊 Levels &amp; Examples</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YuxHgxjkmJJrS8poCxU1WA.png" /></figure><p><strong>Priority inversion example:</strong></p><pre>// Low-priority task holds an actor resource<br>Task(priority: .background) {<br>    await actor.longOperation()    // Holds executor for a while<br>}<br><br>// High-priority task is blocked<br>Task(priority: .userInitiated) {<br>    await actor.quickOperation()   // Blocked; runtime may escalate the other<br>}</pre><blockquote><em>💡 The runtime can temporarily </em><strong><em>escalate</em></strong><em> lower-priority work to avoid deadlocks or poor UX. You don’t micromanage this — Swift does.</em></blockquote><p><strong>Production pattern:</strong></p><pre>actor DataSyncManager {<br>    func syncData(userInitiated: Bool) async throws {<br>        let p: TaskPriority = userInitiated ? .userInitiated : .utility<br>        try await Task(priority: p) { try await performSync() }.value<br>    }<br><br>    func urgentSync() async throws {<br>        try await Task(priority: .userInteractive) { try await performSync() }.value<br>    }<br>}</pre><h3>🧪 Production Case Study — Complete API Client</h3><p>Bringing it together: <strong>TaskLocal</strong> (tracing), <strong>TaskGroup</strong> (parallel), <strong>Priority</strong>, <strong>Continuations</strong>, <strong>Cancellation</strong>, <strong>Sendable</strong>.</p><pre>actor APIClient: Sendable {<br>    @TaskLocal static var requestID: UUID?<br>    @TaskLocal static var userID: String?<br><br>    private let baseURL: URL<br>    private let session: URLSession = .shared<br><br>    init(baseURL: URL) { self.baseURL = baseURL }<br><br>    func fetchDashboard(for userID: String) async throws -&gt; Dashboard {<br>        try await Self.$userID.withValue(userID) {<br>            try await Self.$requestID.withValue(UUID()) {<br>                try await fetchDashboardData()<br>            }<br>        }<br>    }<br><br>    private func fetchDashboardData() async throws -&gt; Dashboard {<br>        try await withThrowingTaskGroup(of: DashboardSection.self) { group in<br>            group.addTask(priority: .userInitiated) { try await self.fetchProfile() }<br>            group.addTask(priority: .userInitiated) { try await self.fetchNotifications() }<br>            group.addTask(priority: .utility)       { try await self.fetchAnalytics() }<br><br>            var sections: [DashboardSection] = []<br><br>            for try await section in group {<br>                try Task.checkCancellation()<br>                sections.append(section)<br>            }<br><br>            return Dashboard(sections: sections)<br>        }<br>    }<br><br>    private func fetchProfile() async throws -&gt; DashboardSection {<br>        try await fetch(from: baseURL.appendingPathComponent(&quot;profile&quot;))<br>    }<br><br>    private func fetchNotifications() async throws -&gt; DashboardSection {<br>        try await fetch(from: baseURL.appendingPathComponent(&quot;notifications&quot;))<br>    }<br><br>    private func fetchAnalytics() async throws -&gt; DashboardSection {<br>        try await fetch(from: baseURL.appendingPathComponent(&quot;analytics&quot;))<br>    }<br><br>    // Continuations bridge legacy URLSession API<br>    private func fetch&lt;T: Decodable&gt;(from url: URL) async throws -&gt; T {<br>        try await withCheckedThrowingContinuation { continuation in<br>            let id = Self.requestID?.uuidString ?? &quot;no-id&quot;<br><br>            let task = session.dataTask(with: url) { data, _, error in<br>                if let error = error {<br>                    logger.error(&quot;[\(id)] ❌ \(url.lastPathComponent): \(error)&quot;)<br>                    continuation.resume(throwing: error); return<br>                }<br><br>                guard let data = data else {<br>                    continuation.resume(throwing: URLError(.badServerResponse)); return<br>                }<br><br>                do {<br>                    let decoded = try JSONDecoder().decode(T.self, from: data)<br>                    continuation.resume(returning: decoded)<br>                } catch {<br>                    continuation.resume(throwing: error)<br>                }<br>            }<br>            task.resume()<br>        }<br>    }<br>}<br><br>// Usage<br>let client = APIClient(baseURL: URL(string: &quot;https://api.example.com&quot;)!)<br>let task = Task {<br>    do {<br>        let dashboard = try await client.fetchDashboard(for: &quot;user123&quot;)<br>        await MainActor.run { displayDashboard(dashboard) }<br>    } catch {<br>        await MainActor.run { showError(error) }<br>    }<br>}<br>// Later - user navigates away:<br>task.cancel()</pre><h3>📈 Task Lifecycle (Mental Model)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*ffLdqmRyVQqbtY-Ib5YxHg.png" /></figure><pre>Cancellation can happen anytime:<br>Task.cancel() → Task.isCancelled = true<br>                     ↓<br>             Next checkCancellation() throws</pre><h3>🧩 Key Takeaways</h3><ul><li><strong>Continuations</strong> bridge legacy callbacks to async/await — resume exactly once; propagate cancellation.</li><li><strong>TaskLocal</strong> carries request/user context without parameter pollution; values auto-restore after scope.</li><li><strong>Sendable</strong> is a compiler contract — prefer value types; classes must <em>prove</em> thread-safety.</li><li><strong>TaskGroup</strong> gives structured parallelism with either fail-fast or collect-all strategies.</li><li><strong>Cancellation</strong> is cooperative — check regularly and clean up with defer.</li><li><strong>Task Priority</strong> guides scheduling; runtime may escalate to avoid priority inversion.</li></ul><blockquote><strong><em>Golden rule:</em></strong><em> Swift Concurrency eliminates </em><strong><em>data races</em></strong><em>, not </em><strong><em>race conditions</em></strong><em>. Timing still matters — design for suspension and reentrancy.</em></blockquote><h3>🔜 Next in Part 5(c) — Wrapping Up</h3><p>We’ll complete the series with:</p><ul><li><strong>AsyncSequence</strong> for streaming live data (network, sensors, UI)</li><li><strong>Swift Concurrency vs GCD</strong> decision frameworks &amp; migration patterns</li><li><strong>Performance tuning &amp; testing</strong> strategies for production apps</li></ul><h3>📚 Series Index</h3><p><a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-1-from-cpu-cores-to-mach-threads-and-thread-pools-d1ebd31ef138">Part 1: From CPU Cores to Mach Threads and Thread Pools</a><br><a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-a-thread-safety-synchronisation-mechanics-42f9714b8cf2">Part 2(a): Thread Safety &amp; Synchronisation Mechanics</a><br><a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-b-actors-isolation-in-swift-concurrency-ec2d567118dc">Part 2(b): Actors &amp; Isolation in Swift Concurrency</a><br><a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-c-debugging-concurrency-in-swift-b4f330b46460">Part 2(c): Debugging Concurrency in Swift</a><br><a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-3-a-foundations-of-grand-central-dispatch-gcd-43343a45dc11">Part 3(a): Foundations of Grand Central Dispatch (GCD)</a><br><a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-3-b-practical-thread-safety-patterns-in-gcd-lld-insights-99cfe665e386">Part 3(b): Practical Thread-Safety Patterns in GCD + LLD Insights</a><br><a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-3-c-gcd-internals-debugging-insights-778122a94fee">Part 3(c): GCD Internals &amp; Debugging Insights</a><br><a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-4-async-await-structured-concurrency-7486fa303aeb">Part 4: async/await &amp; Structured Concurrency</a><br><a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-5-a-actors-executors-the-swift-concurrency-engine-1b3e46d20def">Part 5(a) — Actors &amp; Executors </a><br><strong>Part 5(b) — Practical Patterns (You’re Here) ⭐</strong><br>Part 5(c) — Advanced Patterns <em>(Next)</em></p><p><em>If this helped, share it with your team — and tell me which pattern you want a deeper dive on in Part 5(c)!</em></p><p>Also <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01"><strong>Follow me on LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a853aaed156" width="1" height="1" alt=""><hr><p><a href="https://medium.com/master-ios-concurrency/concurrency-in-ios-part-5-b-practical-swift-concurrency-patterns-6a853aaed156">Concurrency in iOS — Part 5(b): Practical Swift Concurrency Patterns</a> was originally published in <a href="https://medium.com/master-ios-concurrency">Master iOS Concurrency</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency in iOS — Part 2(a): Thread Safety & Synchronisation Mechanics]]></title>
            <link>https://medium.com/master-ios-concurrency/concurrency-in-ios-part-2-a-thread-safety-synchronisation-mechanics-42f9714b8cf2?source=rss----c379d6f0cd70---4</link>
            <guid isPermaLink="false">https://medium.com/p/42f9714b8cf2</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Anubhav Giri]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 03:16:59 GMT</pubDate>
            <atom:updated>2026-06-12T03:17:00.871Z</atom:updated>
            <content:encoded><![CDATA[<h3>Concurrency in iOS — Part 2(a): Thread Safety &amp; Synchronisation Mechanics</h3><p><strong><em>“Two threads walk into a variable. One leaves with the wrong value.”</em></strong></p><blockquote><em>Concurrency in iOS — The Deep Dive Series Exploring how iOS runs your async code — from CPU cores and Mach threads to Swift Actors and structured concurrency.</em></blockquote><p>Series Overview:</p><p>1️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-1-from-cpu-cores-to-mach-threads-and-thread-pools-d1ebd31ef138">Part 1 — From CPU Cores to Mach Threads and Thread Pools</a></p><p>2️⃣ Part 2(a) — Thread Safety &amp; Synchronization Mechanics <em>(you are here)</em></p><p>3️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-b-actors-isolation-in-swift-concurrency-ec2d567118dc">Part 2(b) — Actors, Isolation, and Race Detection</a></p><p><em>Follow the series for upcoming deep dives every week.</em></p><p>In <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-1-from-cpu-cores-to-mach-threads-and-thread-pools-d1ebd31ef138">Part 1</a>, we explored how iOS executes concurrency — from CPU cores and Mach threads to thread pools and queues.<br>Now we zoom in on what happens <em>when those threads start sharing data.</em></p><p>This post is all about <strong>thread safety</strong>, <strong>data races</strong>, and the low-level synchronization tools that keep your app from tearing itself apart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*u20Lti6FE8hCmSmg6oN-8w.png" /></figure><h3>1. What is Thread Safety?</h3><p><strong>Thread-safe code</strong> behaves correctly when accessed from multiple threads at once.<br>Unsafe code doesn’t — because multiple threads mutate shared state simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rXZtDmFM82RQ9V03u3ue_w.png" /></figure><h3>2. The Race Condition Problem</h3><p>A <strong>race condition</strong> happens when two or more threads <em>race</em> to read or write the same variable.<br>The final outcome depends on who wins that race — often unpredictably.</p><h3>Example</h3><pre>class Counter {<br>    var value = 0<br>    func increment() {<br>        value += 1<br>    }<br>}<br><br>let counter = Counter()<br>DispatchQueue.concurrentPerform(iterations: 1000) { _ in<br>    counter.increment()<br>}<br>print(counter.value)  // ❌ Not always 1000</pre><h3>Under the hood</h3><pre>value += 1<br>↓<br>1.️⃣ Load value from memory  <br>2.️⃣ Add 1 (in register)  <br>3.️⃣ Store value back</pre><p>Two threads interleave like this:</p><pre>Thread A -&gt; loads value = 5<br>Thread B -&gt; loads value = 5<br>Thread A -&gt; adds → 6, stores 6<br>Thread B -&gt; adds → 6, stores 6 ← overwrote A’s result</pre><p>Final value = 6 instead of 7. 💥 <em>Race condition.</em></p><h3>3. CPU-Level Perspective</h3><p>At the hardware level:</p><ul><li>Each core has its own <strong>L1/L2 cache</strong>.</li><li>Writes may not immediately propagate to other cores.</li><li>CPU and compiler can <strong>reorder</strong> reads/writes for optimisation.</li></ul><p>Without explicit synchronization, one thread’s updates might not be visible to others — creating <strong>memory visibility bugs </strong>even when you think your code “looks right.”</p><h3>4. Synchronization Primitives in iOS</h3><p>Let’s examine the classic building blocks that enforce mutual exclusion and memory ordering.</p><h3>4.1 Mutex (Mutual Exclusion Lock)</h3><p>Only one thread may hold the lock at a time.</p><pre>let lock = NSLock()<br>lock.lock()<br>counter += 1<br>lock.unlock()</pre><p>Under the hood:</p><ul><li>Backed by pthread_mutex.</li><li>Uses fast user-space spin-then-sleep strategy.</li><li>Falls back to kernel futex (wait/wake) if contention &gt; threshold.</li></ul><p><strong>Cost:</strong> tens of nanoseconds if uncontended → microseconds when blocking.<br><strong>Ideal for:</strong> short critical sections with low contention.</p><h3>4.2 Semaphore</h3><p>A semaphore controls concurrent access to a limited resource.</p><pre>let semaphore = DispatchSemaphore(value: 3)<br>semaphore.wait()   // decrement<br>criticalWork()<br>semaphore.signal() // increment</pre><ul><li>Backed by Mach kernel semaphores.</li><li>Keeps a waiting list of suspended threads.</li></ul><p><strong>Ideal for:</strong> throttling, resource pools, producer-consumer control.</p><h3>4.3 Serial DispatchQueue</h3><p>A DispatchQueue(label:) with no .concurrent attribute executes one task at a time — no explicit locks needed.</p><pre>let serialQueue = DispatchQueue(label: &quot;com.example.sync&quot;)<br>serialQueue.async {<br>    sharedResource.modify()<br>}</pre><ul><li>FIFO order.</li><li>Backed by the system thread pool.</li><li>Avoids deadlocks and priority inversion issues typical of raw locks.</li></ul><p><strong>Ideal for:</strong> isolating mutable state within a queue-bound context.</p><h3>4.4 Dispatch Barrier</h3><p>Allows concurrent reads but exclusive writes.</p><pre>let queue = DispatchQueue(label: &quot;data.queue&quot;, attributes: .concurrent)<br><br>queue.async { readCache() }<br>queue.async { readCache() }<br>queue.async(flags: .barrier) {<br>    updateCache() // waits for reads, blocks new ones<br>}</pre><p>The barrier acts as a <em>fence</em> — all previous blocks finish before the barrier executes.<br>Perfect for caches, maps, or data stores with frequent reads and rare writes.</p><h3>4.5 Atomic Operations and CAS vs Mutex</h3><p><strong>Atomics</strong> guarantee that a read-modify-write sequence happens as one uninterruptible CPU instruction.</p><pre>import Atomics<br><br>let counter = ManagedAtomic&lt;Int&gt;(0)<br>counter.wrappingIncrement(ordering: .relaxed)</pre><h4>How it differs from a mutex</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wgUFGTMyeh-IQmBqf2CNrg.png" /></figure><p>🔍 <strong>CAS loop illustration:</strong></p><pre>repeat {<br>    old = load()<br>    new = old + 1<br>} while !compareAndSwap(old, new)</pre><p>All in user-space, avoiding kernel transitions.<br><strong>Ideal for:</strong> lightweight counters, reference counts, flags.</p><h3>4.6 Condition Variables</h3><p>Coordinate threads — one waits until another signals a condition.</p><pre>let condition = NSCondition()<br>var ready = false<br><br>Thread {<br>    condition.lock()<br>    while !ready { condition.wait() }<br>    print(&quot;Go!&quot;)<br>    condition.unlock()<br>}.start()<br>Thread {<br>    condition.lock()<br>    ready = true<br>    condition.signal()<br>    condition.unlock()<br>}.start()</pre><ul><li>Backed by pthread_cond_t.</li><li>Waiters sleep in the kernel until signaled.<br><strong>Ideal for:</strong> producer-consumer or dependency sequencing.</li></ul><h3>5. Memory Barriers and Visibility</h3><p>Even with locks, CPUs may reorder instructions.<br>A <strong>memory barrier (fence)</strong> forces order and visibility.</p><pre>atomic.store(1, ordering: .release)<br>atomic.load(ordering: .acquire)</pre><p>“Release” ensures prior writes are visible before continuing;<br>“Acquire” ensures subsequent reads see the latest data.</p><h3>6. Deadlocks — When Synchronization Goes Wrong</h3><p>A <strong>deadlock</strong> occurs when two threads wait on each other indefinitely.</p><pre>queue1.sync {<br>    queue2.sync { ... }  // 🚫 both waiting forever<br>}</pre><h3>Common causes</h3><ul><li>Nested locks in inconsistent order</li><li>Calling .sync on a queue that already owns the thread</li><li>Holding locks too long</li><li>Waiting on main queue from main thread</li></ul><h3>Prevention</h3><p>✅ Use consistent lock ordering<br>✅ Prefer serial queues or actors<br>✅ Minimize critical sections<br>✅ Never block .main queue</p><h3>7. Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aD0Tr_ZB_2_VqlKNevuvUA.png" /></figure><h3>8. Key Takeaways</h3><p>✅ Race conditions = unsynchronized reads/writes on shared mutable state<br>✅ Locks guarantee mutual exclusion, atomics guarantee atomicity<br>✅ Serial queues simplify thread safety without manual locks<br>✅ Barriers enable safe read-write patterns<br>✅ Fewer locks → less contention → better battery life</p><h3>🚀 Next Up — Part 2(b): From Locks to Actors and Concurrency Debugging</h3><p>In the next post we’ll explore <strong>how Swift Concurrency removes these locks altogether</strong> using the Actor model, structured isolation, and language-level thread safety.<br>We’ll also walk through <strong>Thread Sanitizer</strong> output and <strong>deadlock debugging</strong> in Xcode.</p><p>Stay tuned for <strong>Part 2(b) → From Locks to Actors and Debugging Concurrency</strong> 🚀</p><p>Follow me on LinkedIn: <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01">www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42f9714b8cf2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/master-ios-concurrency/concurrency-in-ios-part-2-a-thread-safety-synchronisation-mechanics-42f9714b8cf2">Concurrency in iOS — Part 2(a): Thread Safety &amp; Synchronisation Mechanics</a> was originally published in <a href="https://medium.com/master-ios-concurrency">Master iOS Concurrency</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency in iOS — Part 2(b): Actors & Isolation in Swift Concurrency]]></title>
            <link>https://medium.com/master-ios-concurrency/concurrency-in-ios-part-2-b-actors-isolation-in-swift-concurrency-ec2d567118dc?source=rss----c379d6f0cd70---4</link>
            <guid isPermaLink="false">https://medium.com/p/ec2d567118dc</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Anubhav Giri]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 03:16:34 GMT</pubDate>
            <atom:updated>2026-06-12T03:16:36.031Z</atom:updated>
            <content:encoded><![CDATA[<h3>Concurrency in iOS — Part 2(b): Actors &amp; Isolation in Swift Concurrency</h3><blockquote><em>“Locks protect code. Actors protect </em>state<em>.”</em></blockquote><p>In <a href="https://anubhavgiri01.medium.com/concurrency-in-ios-part-2-a-thread-safety-synchronisation-mechanics-42f9714b8cf2">Part 2(a)</a> we explored how thread safety was traditionally achieved with <strong>locks, semaphores, and atomics</strong>.<br>Now we move up a layer — into <strong>Swift Concurrency</strong>, where safety is guaranteed not by discipline but by the <em>type system</em>.</p><p>This part explains how <strong>actors</strong>, <strong>Sendable</strong>, and <strong>structured concurrency</strong> replace manual synchronization while keeping your code performant and predictable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*H54R0U9Z2bsPRalkP9Vt_g.png" /></figure><h3>⚙️ 1. Why Swift Introduced Actors</h3><p>Manual synchronization is fragile:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-6mLoa-n9Cc1vKW855YFrQ.png" /></figure><p>Swift Concurrency introduces a higher-level abstraction — <strong>actors</strong> — that serialize access automatically and let the compiler enforce thread safety.</p><h3>🧩 2. What is an Actor?</h3><p>An <strong>actor</strong> is a reference type whose mutable state can only be accessed <strong>inside the actor’s own isolation context</strong>.</p><pre>actor Counter {<br>    private var value = 0<br>    func increment() { value += 1 }<br>    func current() -&gt; Int { value }<br>}<br><br>let counter = Counter()<br>await counter.increment()<br>print(await counter.current())</pre><p>✅ No locks.<br>✅ No data races.<br>✅ Compiler guarantees isolation.</p><p>Under the hood, each actor owns a <strong>serial executor</strong>. Tasks targeting that actor run one-by-one — much like a private serial DispatchQueue, but fully managed by Swift’s runtime.</p><h3>🔄 3. Understanding Reentrancy (Correctly)</h3><p>When an actor function hits an await, it <strong>may suspend</strong>, allowing other tasks waiting on that actor to run first.<br>This is called <strong>reentrancy</strong> — it improves responsiveness without violating isolation.</p><pre>actor Inventory {<br>    private var stock: [String: Int] = [&quot;book&quot;: 1]<br><br>    func reserve(item: String) async throws {<br>        guard let qty = stock[item], qty &gt; 0 else { throw OutOfStock() }<br>        try await chargeUser()      // suspension point<br>        guard let updated = stock[item], updated &gt; 0 else { throw OutOfStock() }<br>        stock[item] = updated - 1<br>    }<br>}</pre><p>While suspended, other tasks may change stock.<br>Swift’s type system keeps access safe, but you must reason about <em>logical correctness</em> across await:</p><blockquote><em>🧠 Snapshot critical data before </em><em>await and re-validate it after.</em></blockquote><p>There is no “non-reentrant actor” in released Swift — reentrancy is the normal, safe behavior.</p><h3>🔐 4. The Sendable Protocol — Type-Safe Boundaries</h3><p>Sendable defines whether a type’s value can safely cross concurrency domains.</p><pre>import Foundation<br>import os<br><br>struct User: Sendable {<br>    let id: Int<br>    let name: String<br>}<br><br>final class MutableBox&lt;T&gt; {<br>    var value: T        // ❌ Not Sendable – mutable class<br>    <br>    init(value: T) {<br>        self.value = value<br>    }<br>}<br><br>final class SafeBox&lt;T: Sendable&gt;: @unchecked Sendable {<br>    private let lock = OSAllocatedUnfairLock()<br>    private var _value: T<br>    <br>    init(_ v: T) {<br>        _value = v<br>    }<br>    var value: T {<br>        get {<br>            lock.withLock {<br>                _value<br>            }<br>        }<br>        set { lock.withLock { _value = newValue } }<br>    }<br>}</pre><p>If you pass a non-Sendable type between tasks, the compiler warns you — preventing hidden shared-state races at compile-time.</p><h3>Common Sendable Rules</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TGuWySsobrLwJf6_PR6cFQ.png" /></figure><h3>🔁 5. Crossing Isolation Domains Safely</h3><p>Actors isolate mutable state; when you pass data out, ensure it’s <strong>value-semantics</strong> or <strong>Sendable</strong>.</p><pre>actor UserStore {<br>    private var cache: [Int: User] = [:]<br>    <br>    func upsert(_ user: User) {<br>        cache[user.id] = user<br>    }<br>    <br>    func user(for id: Int) -&gt; User? {<br>        cache[id]<br>    }   // copy-by-value<br>}<br><br>struct User {<br>    let id: Int<br>}</pre><p>Never expose references to the actor’s internal storage.<br>If you must share a reference, make it immutable or wrap it in a Sendable container (like the SafeBox above).</p><h3>🧱 6. Structured Concurrency &amp; Task Groups</h3><p>withTaskGroup lets you spawn concurrent child tasks with <strong>automatic lifetime and error management</strong>.</p><pre>func fetchProfiles(_ ids: [Int]) async throws -&gt; [Profile] {<br>    try await withThrowingTaskGroup(of: Profile.self) { group in<br>        for id in ids {<br>            group.addTask { try await fetchProfile(id) }<br>        }<br>        var result: [Profile] = []<br>        for try await p in group { result.append(p) }<br>        return result<br>    }<br>}</pre><h3>Why It’s Safer</h3><ul><li>Children cancel automatically if a sibling throws.</li><li>Errors propagate cleanly — no manual counting or semaphores.</li><li>Structured lifetime: children never outlive their parent scope.</li></ul><blockquote><em>💡 Use non-throwing groups (</em><em>withTaskGroup) if you want to collect partial successes.</em></blockquote><h3>⚡ 7. Performance &amp; Actor Contention</h3><p>Actors serialize access; heavy contention can throttle concurrency.</p><p><strong>Tips for throughput:</strong></p><ul><li>Split hot data across <strong>multiple actors</strong> (sharding).</li><li>Keep actor functions short — move I/O outside.</li><li>Avoid frequent hops between executors (@MainActor ↔ background).</li><li>Profile with Instruments → <em>Time Profiler → Thread States.</em></li></ul><pre>actor ShardedCache {<br>    private var shards: [Int: [String: Data]] = [:]<br>    func put(_ key: String, data: Data) {<br>        let bucket = key.hashValue &amp; 0xF<br>        var table = shards[bucket, default: [:]]<br>        table[key] = data<br>        shards[bucket] = table<br>    }<br>}</pre><h3>🧩 8. Practical Patterns for Isolation</h3><h3>Snapshot Before Await</h3><pre>actor Cart {<br>    private var items: [String: Int] = [:]<br><br>    func checkout() async throws {<br>        let snapshot = items<br>        let total = try await calculateTotal(snapshot)<br>        try await charge(total)<br>        items.removeAll()<br>    }<br>}</pre><h3>Cancellation-Aware Work</h3><pre>func process(_ docs: [Doc]) async throws {<br>    for doc in docs {<br>        try Task.checkCancellation()<br>        try await index(doc)<br>    }<br>}</pre><h3>Actor + TaskGroup Combo</h3><pre>actor ImageAggregator {<br>    func fetchAll(_ ids: [String]) async throws -&gt; [UIImage] {<br>        try await withThrowingTaskGroup(of: UIImage.self) { group in<br>            for id in ids { group.addTask { try await self.fetchImage(id) } }<br>            var results: [UIImage] = []<br>            for try await img in group { results.append(img) }<br>            return results<br>        }<br>    }<br>}</pre><h3>🧭 9. Key Takeaways</h3><p>✅ Actors isolate mutable state; only one task accesses it at a time.<br>✅ Reentrancy is safe — snapshot state before await, re-validate after.<br>✅ Sendable enforces compile-time safety for cross-thread data.<br>✅ Structured Concurrency gives you safe parallelism with automatic error handling.<br>✅ Performance depends on design — minimize contention and executor hops.</p><h3>📚 What’s Next</h3><p>In <strong>Part 2(c): Debugging Concurrency in Swift</strong>, we’ll use:</p><ul><li><strong>Thread Sanitizer (TSan)</strong> to detect data races</li><li><strong>Concurrency Debugger (Xcode 15+)</strong> to inspect active tasks and actors</li><li>A practical playbook for diagnosing isolation violations and cancellation bugs</li></ul><p>🧠 <strong>Concurrency in iOS — The Deep Dive Series</strong><br>1️⃣ <a href="https://anubhavgiri01.medium.com/concurrency-in-ios-part-1-from-cpu-cores-to-mach-threads-and-thread-pools-d1ebd31ef138">Part 1 — From CPU Cores to Mach Threads and Thread Pools</a><br>2️⃣ <a href="https://medium.com/@anubhavgiri01/concurrency-in-ios-part-2-a-thread-safety-synchronisation-mechanics-42f9714b8cf2">Part 2(a) — Thread Safety &amp; Synchronization Mechanics</a><br>3️⃣ <strong>Part 2(b) — Actors &amp; Isolation in Swift Concurrency</strong> <em>(you are here)</em><br>4️⃣ Part 2(c) — Debugging Concurrency in Swift (TSan &amp; Concurrency Debugger) [<strong><em>Next</em></strong>]</p><p>Find this Helpful — Follow me on LinkedIn: <a href="http://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01">www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&amp;followMember=anubhavgiri01</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec2d567118dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/master-ios-concurrency/concurrency-in-ios-part-2-b-actors-isolation-in-swift-concurrency-ec2d567118dc">Concurrency in iOS — Part 2(b): Actors &amp; Isolation in Swift Concurrency</a> was originally published in <a href="https://medium.com/master-ios-concurrency">Master iOS Concurrency</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>