【Swift/非同期/同期/swift concurrency】Actorでキャッシュ管理

SwiftUI

写真撮影時のキャッシュで
ハーフ撮影2in1と二重露光の時に1枚目を撮影したデータをキャッシュ(メモリ上)した状態にしておきますが
設定変更などでリセット(削除)したい時があります。

Task { @CameraOutputActor( globalActor ) で撮影処理を行っています。ここだけでキャッシュ管理したら良いのですが、使わない時リセットするのは @MainActorや他の場所から操作したい場合。
(これは普通に @MainActorからでも Task { @CameraOutputActorで処理したら問題ないです)
( @globalActorについては別記事に書きます
しかし並列処理や他のTaskやdispatchQueueからも自由にキャッシュとして使用できるもの(変数)が欲しいときActorでロック的に使用できるので良いですよね

これはキャッシュには良いけどフラグなど高頻度でアクセスするとダメです(後述

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


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をコピーしました