【Swift/非同期/同期/swift concurrency】DispatchQueue / GlobalActor / Actor / Atomic について整理!| Mastering Swift Concurrency: Organizing DispatchQueue, GlobalActor, Actor, and Atomic

SwiftUI

カメラアプリをリファクタリングしていて、まあ普通に動いていますが
なかなか面白いのですが、簡単にこれが良い、これがダメと判断するのは難しいですね^_^;
AtomicはiOS18以降 swift6で導入されたようで、今回は使えないのですが便利ですね

cameraQueue / videoQueue / Task / Task { @GlobalActor の使い分けが重要
( @MainActorはUIと連動するとして。
などなどある程度の動きはわかって作っていましたが、何回もリファクタリングしてここにきてしっかり理解し直しました^^
あ、ここはこの機能を使うとさらにスマートだな!と^^v

https://umi.grtlab.com
umi カメラというフィルム調カメラアプリの開発をしています!ぜひ使ってください!

ここまで議論してきたSwiftの並行処理の道具たちは、それぞれ「得意分野」が異なります。混乱しやすいポイントを整理して比較リストにまとめました。

並行処理メカニズム 比較表

ツール種類主な目的実行順序 (FIFO)特徴・使いどころ
DispatchQueue (Serial)キュー (GCD)厳密な順序を守るデバイス制御100%保証カメラセッションの操作 (start/stop) など、絶対に順番が狂ってはいけない処理に最適。
GlobalActor (@MainActor等)アクター (Swift)特定の役割を持つクラス群を隔離保証されない (再入可能)@MainActor のように、UI更新や特定のロジック群を一つの「個室」に縛り付けるのに便利。
Actor (小文字 actor)型 (Swift)**データ(状態)**を安全に守る保証されない (再入可能)Services/Cache/ のように、変数の競合を防ぎたい「データの保管庫」に最適。
Atomicハードウェア操作極限の高速化とスレッド安全N/Aawait すら不要。1秒間に何百回も書き換わるフラグやカウントに使用する最終兵器。

各ツールの深掘り解説

1. DispatchQueue (Serial)

  • 強み: 投げた順に実行されることが物理的に保証されている。
  • 弱み: 中で重い処理をすると、そのキュー全体が止まってしまう。
  • 結論: カメラデバイスの「司令塔」として残すべき場所。

2. GlobalActor

  • 強み: クラスやメソッドに属性として貼れるため、広範囲の同期が楽。
  • 弱み: await で中断している間に他の処理が割り込める(再入可能性)。
  • 結論: 「カメラシステム全体」や「UI全体」といった、大きな役割ごとの交通整理に使う。

3. Actor

  • 強み: データの読み書きの競合をコンパイルレベルで防ぐ。
  • 弱み: 外部から触るたびに await が必要。
  • 結論: キャッシュ、データベース、ユーザー設定など、「守るべきデータ」がある場所に使う。

4. Atomic

  • 強み: アクターの「個室に入る(コンテキストスイッチ)」コストがない。
  • 弱み: 複雑なロジックは守れない(1つの値のみ)。
  • 結論: パフォーマンスが最優先される小さなフラグ管理に使う。

整理された「カメラアプリ」の棲み分け図

  1. 司令塔 (DispatchQueue): セッションの start/stop を FIFO で管理。
  2. 実行部 (Task.detached): DispatchQueue から重い仕事を切り離して裏で実行。
  3. 倉庫 (actor): 切り離された仕事の結果(画像データ)を安全に保存。
  4. 表示 (@MainActor): 倉庫から取り出した画像を SwiftUI で表示。

https://umi.grtlab.com
umi カメラというフィルム調カメラアプリの開発をしています!ぜひ使ってください!
umi Camera | Vintage Film Retro , iPhone Free app I’m developping!!!

Mastering Swift Concurrency: Organizing DispatchQueue, GlobalActor, Actor, and Atomic


In modern iOS development, choosing the right tool for synchronization is crucial for both performance and safety. Here is a definitive guide to comparing the four essential mechanisms.

Comparison Table: Synchronization Mechanisms

ToolCategoryPrimary PurposeExecution Order (FIFO)Best Use Case
DispatchQueue (Serial)Queue (GCD)Ensuring Strict Order for hardware/sequential logic100% GuaranteedDevice Control: Camera sessions (start/stop) where order is critical.
GlobalActor (e.g., @MainActor)Actor (Swift)Isolating Specific Roles or global domainsNot Guaranteed (Reentrant)Architectural Isolation: Wiring UI updates to @MainActor or custom logic to a specific thread.
Actor (keyword actor)Type (Swift)Protecting Data (State) from racesNot Guaranteed (Reentrant)Data Storage: Services like ImageCache where you protect shared mutable state.
Atomic (e.g., Atomic<Int>)Low-level OpExtreme Performance for simple valuesN/AHigh-frequency Flags: Counters or flags updated thousands of times per second without await overhead.

Deep Dive: Choosing the Right Tool

1. DispatchQueue (Serial)

  • Strength: Physically guarantees that tasks are executed in the exact order they were submitted.
  • Weakness: If a heavy task is executed, the entire queue is blocked, leading to potential “hangups.”
  • Verdict: Use this as the “Mission Control” for hardware-related operations.

2. GlobalActor

  • Strength: Can be applied as an attribute (e.g., @PhotoOutputActor) to entire classes or methods, making broad synchronization easy.
  • Weakness: Reentrancy. While one task is suspended at an await, another task can enter the “room.”
  • Verdict: Use this to define “Work Zones” like a dedicated thread for image processing.

3. Actor

  • Strength: Prevents data races at the compiler level. Encapsulates state perfectly.
  • Weakness: Requires await for every external access, which can lead to “actor hopping” overhead if overused.
  • Verdict: The gold standard for “Warehouses” like Caches, Databases, or UserSettings.

4. Atomic

  • Strength: No “Context Switching” cost. It’s faster than an Actor because it doesn’t involve the Swift Concurrency runtime’s task scheduling.
  • Weakness: Can only protect simple, individual values; cannot protect complex logic or multiple variables together.
  • Verdict: Use for low-latency flags where the overhead of await is unacceptable.

The Ultimate “Camera App” Architecture

To build a high-performance camera app, combine these tools based on their strengths:

  1. The Commander (DispatchQueue): Handles AVCaptureSession operations to ensure strict FIFO order.
  2. The Worker (Task.detached): Offloads heavy lifting (image conversion) from the Commander immediately.
  3. The Warehouse (actor): Safely stores the results (processed images) in a thread-safe cache.
  4. The Presenter (@MainActor): Fetches data from the Warehouse and renders it on the screen.

https://umi.grtlab.com
umi カメラというフィルム調カメラアプリの開発をしています!ぜひ使ってください!
umi Camera | Vintage Film Retro , iPhone Free app I’m developping!!!


お気軽にコメントください!

スパム対応のためコメント認証に数日かかることがありますが、お気軽にコメントいただけると嬉しいです^^

コメント

タイトルとURLをコピーしました