📚

Swift Concurrency用語完全ガイド

に公開

目次


1. はじめに

本記事について

本記事は、筆者が Swift Concurrency の用語を正確に理解するために、Swift Evolution Proposals や The Swift Programming Language(公式ドキュメント)を調査した内容をまとめたものです。

自分の勉強のために整理したものなので、解釈が間違っている可能性があります。気になる箇所があれば、ぜひご自身で出典元を確認してください。また、誤りを見つけた場合はコメントで教えていただけると助かります。

対象読者

Swift Concurrencyの基本的な概念(Actor、async/await、Sendableなど)は理解しているものの、細かい用語の使い分けが曖昧になりがちな方を対象としています。

例えば、こんな疑問を持ったことはありませんか?

  • Sendable と sending の違いは?
  • nonisolated と non-Sendable は何が違う?
  • MainActor と main thread の違いは?
  • Suspension と Blocking は何が違う?

本記事の構成

各用語について以下の形式で整理しています:

  • 公式定義(英語): Swift Evolution ProposalsやThe Swift Programming Languageからの引用
  • 出典: 定義の出典元へのリンク
  • 日本語での定義: 公式定義に基づいた日本語での説明

2. Actor・Isolation 関連

Actor Isolation

項目 内容
公式定義(英) "Actor isolation is how actors protect their mutable state."
詳細 "For actors, the primary mechanism for this protection is by only allowing their stored instance properties to be accessed directly on self."
出典 SE-0306: Actors

The Swift Programming Language での説明:

"Swift guarantees that only code running on an actor can access that actor's local state. This guarantee is known as actor isolation."

出典: The Swift Programming Language - Concurrency

日本語での定義:
Actor isolation とは、Actor が自身の mutable state(可変状態)を保護する仕組みである。Actor 上で実行されているコードのみがその Actor のローカル状態にアクセスできることを Swift が保証する。


Actor-isolated

項目 内容
公式定義(英) "All declarations on an instance of an actor, including stored and computed instance properties, instance methods, and instance subscripts, are all actor-isolated by default."
補足 "A declaration that is not actor-isolated is non-isolated and cannot synchronously access any actor-isolated declaration."
出典 SE-0306: Actors

日本語での定義:
Actor-isolated とは、Actor インスタンス上の宣言(stored/computed プロパティ、メソッド、subscript)がデフォルトで持つ状態である。actor-isolated でない宣言は nonisolated であり、actor-isolated な宣言に同期的にアクセスできない。


Cross-actor Reference

項目 内容
公式定義(英) "A reference to an actor-isolated declaration from outside that actor is called a cross-actor reference."
許容条件 1. immutable state への参照、2. 非同期関数呼び出し経由
制約 "all cross-actor references can only involve types that conform to Sendable"
出典 SE-0306: Actors

日本語での定義:
Cross-actor reference とは、Actor の外部から actor-isolated な宣言への参照である。immutable state への参照か、非同期関数呼び出し経由でのみ許可される。すべての cross-actor reference は Sendable に準拠した型のみを扱える。


Isolation Domain

項目 内容
公式定義(英) "Code running in distinct isolation domains can execute concurrently, and Sendable checking defines away concurrent access to shared mutable state."
特性 "An isolation region can be associated with a specific isolation domain associated with a task, protected by an actor instance or a global actor, or disconnected from any specific isolation domain."
出典 SE-0414: Region based Isolation

日本語での定義:
Isolation domain とは、異なる domain で実行されるコードが並行に実行可能な、Actor や Task に関連付けられた実行コンテキストである。Sendable チェックにより、共有 mutable state への並行アクセスを防止する。isolation region は特定の isolation domain に関連付けられるか、どの domain にも関連付けられない(disconnected)状態をとる。


Isolation Context(用語整理)

項目 内容
公式定義 Swift Evolution Proposals で正式に定義されていない
使用例 SE-0313: "actor types should be able to conform to protocols with the assumption that the conformance is only used within the actor's isolation context"
出典 SE-0313, SE-0392 での文脈的使用のみ

補足:
"Isolation context" は Swift Evolution Proposals で正式に定義されている用語ではない。公式ドキュメントでは主に "isolation domain" が使用される。"isolation context" が使われる場合は、特定の Actor や Task に関連付けられた実行文脈を指すことが多い。本記事では公式用語である "isolation domain" を一貫して使用する。


Concurrency Domain

項目 内容
公式定義(英) "Inside of a task or an instance of an actor, the part of a program that contains mutable state, like variables and properties, is called a concurrency domain."
Isolation Domain との関係 実質的に同義として使用されることが多い
出典 The Swift Programming Language - Concurrency

日本語での定義:
Concurrency domain とは、Task や Actor インスタンスの内部で、変数やプロパティなどの mutable state を含むプログラムの部分である。Isolation domain と実質的に同義として使用される。


Isolation Boundary

項目 内容
公式定義(英) "non-Sendable values... cannot be transferred over an isolation boundary"
境界の位置 Actor と Task の境界によって決定される。異なる isolation domain 間の境界
Sendable との関係 Sendable に準拠した型のみが isolation boundary を越えて転送可能(Region-based isolation 導入前)
出典 SE-0414: Region based Isolation

日本語での定義:
Isolation boundary とは、異なる isolation domain 間の境界である。Actor や Task の境界によって決定される。従来は Sendable に準拠した型のみがこの境界を越えて転送可能だったが、Region-based isolation(SE-0414)の導入により、non-Sendable な値でも転送後に元の場所で使用されないことが証明できれば、安全に境界を越えられるようになった。


Isolation Region (Region-based Isolation)

項目 内容
公式定義(英) "An isolation region is a set of non-Sendable values that can only be aliased or reachable from values that are within the isolation region."
技術的定義 "two values x and y are defined to be within the same isolation region at a program point p if: (1) x may alias y at p; (2) x or a property of x might be referenceable from y via chained access."
目的 "a new control flow sensitive diagnostic that determines whether a non-Sendable value can safely be transferred over an isolation boundary."
出典 SE-0414: Region based Isolation

日本語での定義:
Isolation region とは、その region 内の値からのみエイリアスまたは到達可能な non-Sendable 値の集合である。2つの値 x と y が同じ isolation region にあるとは、(1) x が y のエイリアスである可能性がある、または (2) x またはそのプロパティが連鎖アクセスを通じて y から参照可能である、のいずれかを満たすことである。


Disconnected Region

項目 内容
公式定義(英) "A disconnected isolation region is a region that consists only of non-Sendable values and is not associated with a specific isolation domain."
重要な特性 Disconnected region は特定の isolation domain に紐づいていないため、isolation boundary を越えて安全に転送できる
sending との関係 "the value is in a disconnected region and we say that such a value is a sending value" (SE-0430)
出典 SE-0414: Region based Isolation

日本語での定義:
Disconnected region とは、non-Sendable 値のみで構成され、特定の isolation domain に関連付けられていない isolation region である。どの isolation domain にも紐づいていないため、isolation boundary を越えて安全に転送可能である。sending 修飾子はこの disconnected 状態にある値を示す。


Global Actor

項目 内容
公式定義(英) "A global actor is a globally-unique actor identified by a type."
実装要件 "A global actor is a type that has the @globalActor attribute and contains a static property named shared that provides a shared instance of an actor."
通常の Actor との違い "When the data that needs to be isolated is scattered across a program, or is representing some bit of state that exists outside of the program, bringing all of that code and data into a single actor instance might be impractical."
出典 SE-0316: Global Actors

日本語での定義:
Global actor とは、型によって識別されるグローバルに一意な Actor である。@globalActor 属性を持ち、shared という static プロパティで Actor の共有インスタンスを提供する。プログラム全体に散在するデータや、プログラム外部に存在する状態を保護する場合に使用する。


MainActor

項目 内容
公式定義(英) "The main actor is a global actor that describes the main thread."
目的 "A primary motivator of global actors is to apply the actor model to the state and operations that can only be accessed by the main thread."
実装詳細 "For systems that use Apple's Dispatch library as the underlying concurrency implementation, the main actor uses a custom executor that wraps the main dispatch queue."
出典 SE-0316: Global Actors

The Swift Programming Language での補足:

"The main actor is closely related to the main thread, but they're not the same thing."

日本語での定義:
Main actor とは、メインスレッドを表す global actor である。メインスレッドでのみアクセス可能な状態と操作に Actor モデルを適用するために使用する。main actor と main thread は密接に関連しているが、同一ではない。


nonisolated

項目 内容
公式定義(英) "Instance declarations on an actor type implicitly have an isolated self. However, one can disable this implicit behavior using the nonisolated keyword"
制約 "The types involved in a non-isolated declaration must all be Sendable, because a non-isolated declaration can be used from any actor or concurrently-executing code."
プロトコル適合 "non-isolated functions don't have access to actor state, so they are free to satisfy synchronous protocol requirements of any kind"
出典 SE-0313: Improved control over actor isolation

日本語での定義:
nonisolated とは、Actor 型のインスタンス宣言が暗黙的に持つ isolated self を無効化するキーワードである。nonisolated な宣言で扱う型はすべて Sendable でなければならない。nonisolated な関数は Actor の状態にアクセスできないため、任意の同期プロトコル要件を満たすことができる。


nonisolated(unsafe)

項目 内容
公式定義(英) "The attribute nonisolated(unsafe) can be used to annotate the global variable (or any form of storage)."
用途 開発者が静的なデータ分離チェックをオプトアウトし、独自の同期機構(グローバルロックなど)に依存する場合
警告 "without correct implementation of a synchronization mechanism to achieve data isolation, dynamic run-time analysis from exclusivity enforcement or tools such as Thread Sanitizer could still identify failures."
導入 Swift 5.10
出典 SE-0412: Strict concurrency for global variables

日本語での定義:
nonisolated(unsafe) とは、グローバル変数やその他のストレージに付与できる属性で、静的なデータ分離チェックをオプトアウトする。開発者が独自の同期機構(ロックなど)でデータ分離を保証する場合に使用する。正しい同期機構がない場合、Thread Sanitizer などで実行時に問題が検出される可能性がある。


nonisolated(nonsending)

項目 内容
公式定義(英) "Async functions annotated with nonisolated(nonsending) will always run on the caller's actor"
用途 呼び出し元のアクターで実行を継続し、non-Sendable な値を安全に渡す
動作 "This behavior is accomplished by implicitly passing an optional actor parameter to the async function. The function will run on this actor's executor."
位置づけ 移行期間用の明示的な構文。将来的には nonisolated async 関数のデフォルト動作となる予定
導入 Swift 6.2 (SE-0461)
出典 SE-0461: Run nonisolated async functions on the caller's actor by default

日本語での定義:
nonisolated(nonsending) とは、async 関数が常に呼び出し元の Actor 上で実行されることを示す属性である。暗黙的にオプショナルな Actor パラメータを渡すことで実現される。これにより non-Sendable な値を安全に扱える。将来的には nonisolated async 関数のデフォルト動作となる予定。


@concurrent

項目 内容
公式定義(英) "Async functions can be declared to always switch off of an actor to run using the @concurrent attribute"
制約 "Only (implicitly or explicitly) nonisolated functions can be marked with @concurrent"
従来動作との関係 従来の "nonisolated async functions never run on an actor's executor" という動作を明示的に指定
導入 Swift 6.2 (SE-0461)
出典 SE-0461

日本語での定義:
@concurrent とは、async 関数が常に Actor から離れて実行されることを宣言する属性である。nonisolated な関数にのみ付与できる。従来の nonisolated async 関数の動作(Actor の executor 上で実行されない)を明示的に指定する。


3. Sendable・型システム関連

Sendable

項目 内容
公式定義(英) "types that are allowed to be safely passed across concurrency domains by copying the value"
含まれるもの "value-semantic types, references to immutable reference types, internally synchronized reference types, @Sendable closures"
コンパイラの役割 "The compiler rejects any attempts to pass data across concurrency domains, e.g. rejecting cases where the argument or result of an actor message send or structured concurrency call does not conform to the Sendable protocol"
出典 SE-0302: Sendable and @Sendable closures

The Swift Programming Language での説明:

"A type that can be shared from one concurrency domain to another is known as a sendable type."

Sendable になる3つの方法:

  1. Value type で mutable state が他の sendable data で構成
  2. Mutable state を持たず、immutable state が sendable data で構成
  3. Mutable state の安全性を保証するコード(@MainActor やシリアライズ)を持つ

日本語での定義:
Sendable とは、値のコピーによって concurrency domain 間で安全に渡すことができる型である。value 型、immutable な参照型への参照、内部で同期を行う参照型、@Sendable クロージャが含まれる。コンパイラは Sendable に準拠しない型を concurrency domain 間で渡そうとする試みを拒否する。


sending

項目 内容
公式定義(英) "A function parameter or result that is annotated with sending is required to be disconnected at the function boundary"
Disconnected の意味 "the value is in a disconnected region and we say that such a value is a sending value"
Sendable との違い Sendable は型レベルの制約、sending は値レベルの制約(所有権移転による安全性)
名前の由来 "we are not actually transferring the parameter into another isolation domain...we are requiring that the value...be in a disconnected region and thus have the capability to be sent"
導入 Swift 6
出典 SE-0430: sending parameter and result values

日本語での定義:
sending とは、関数パラメータまたは戻り値が関数境界で disconnected(切り離された状態)であることを要求する修飾子である。値が disconnected region にあり、送信可能な能力を持つことを示す。Sendable が型レベルの制約であるのに対し、sending は値レベルの制約であり、non-Sendable な値でも所有権の移転によって安全に渡せる。


4. Task 関連

Task

項目 内容
公式定義(英) "A task is the basic unit of concurrency in the system. Every asynchronous function is executing in a task."
Thread との関係 "a task is to asynchronous functions, what a thread is to synchronous functions."
出典 SE-0304: Structured Concurrency

The Swift Programming Language での説明:

"A task is a unit of work that can be run asynchronously as part of your program. All asynchronous code runs as part of some task. A task itself does only one thing at a time, but when you create multiple tasks, Swift can schedule them to run simultaneously."

日本語での定義:
Task とは、システムにおける並行処理の基本単位である。すべての非同期関数は Task 内で実行される。Task と非同期関数の関係は、Thread と同期関数の関係に相当する。Task 自体は一度に1つのことしか行わないが、複数の Task を作成すると Swift がそれらを同時に実行するようスケジュールできる。


Structured Concurrency

項目 内容
公式定義(英) 高レベルの task とその子コンポーネント task を階層的に組織化し、優先度・キャンセル・デッドラインを管理する手法
特徴 親子関係が明示的で、情報が階層を通じて自然に流れる
出典 SE-0304: Structured Concurrency

The Swift Programming Language での説明:

"Because of the explicit relationship between tasks and task groups, this approach is called structured concurrency."

利点:

  • 親タスクで子タスクの完了を待ち忘れることがない
  • 子タスクの優先度を上げると親の優先度も自動的に上がる
  • 親タスクがキャンセルされると子タスクも自動的にキャンセル
  • Task-local values が子タスクに効率的に自動伝播

日本語での定義:
Structured concurrency とは、Task と Task Group の間の明示的な親子関係に基づく並行処理の構造化手法である。親 Task で子 Task の完了を待ち忘れることがなく、優先度の自動エスカレーション、キャンセルの自動伝播、Task-local values の効率的な伝播が保証される。


Unstructured Concurrency

項目 内容
公式定義(英) "Unstructured tasks are not able to utilize some of the optimization techniques wrt. allocation and metadata propagation as child-tasks are, however they remain a very important building block especially for more free-form usages."
種類 Task { } (周囲のコードと同様に実行), Task.detached { } (より独立して実行)
出典 SE-0304: Structured Concurrency

The Swift Programming Language での説明:

"Unlike tasks that are part of a task group, an unstructured task doesn't have a parent task. You have complete flexibility to manage unstructured tasks in whatever way your program needs, but you're also completely responsible for their correctness."

日本語での定義:
Unstructured concurrency とは、親 Task を持たない独立した Task による並行処理である。子 Task のような最適化は利用できないが、自由な形式での使用に重要な構成要素である。Task の管理に完全な柔軟性があるが、正確性の責任も完全に開発者にある。


Child Task

項目 内容
公式定義(英) "An asynchronous function can create a child task. Child tasks inherit some of the structure of their parent task, including its priority, but can run concurrently with it."
出典 SE-0304: Structured Concurrency

日本語での定義:
Child task とは、非同期関数が作成できる子タスクである。親タスクの構造の一部(優先度など)を継承しつつ、親タスクと並行して実行できる。


Task Cancellation

項目 内容
公式定義(英) "A task can be cancelled asynchronously by any context that has a reference to a task"
重要な特性 "Cancellation has no effect at all unless something checks for cancellation."
チェック方法 Task.checkCancellation() (throws), Task.isCancelled (property)
出典 SE-0304: Structured Concurrency

The Swift Programming Language での説明:

"Swift concurrency uses a cooperative cancellation model. Each task checks whether it has been canceled at the appropriate points in its execution, and responds to cancellation appropriately."

日本語での定義:
Task cancellation とは、Task への参照を持つ任意のコンテキストから非同期にキャンセルできる機構である。Swift は協調的キャンセルモデルを採用しており、キャンセルのチェックを行わない限りキャンセルは効果を持たない。Task は実行中の適切なポイントでキャンセルをチェックし、適切に応答する必要がある。


Task Priority

項目 内容
公式定義(英) "A task is associated with a specific priority"
役割 "Task priority may inform decisions an executor makes about how and when to schedule tasks submitted to it."
出典 SE-0304: Structured Concurrency

日本語での定義:
Task priority とは、Task に関連付けられた優先度である。Executor が Task をいつどのようにスケジュールするかの判断に影響を与える。


5. async/await・実行モデル関連

Suspension Point

項目 内容
公式定義(英) "A suspension point is a point in the execution of an asynchronous function where it has to give up its thread."
マーカー await キーワード
出典 SE-0296: Async/await

The Swift Programming Language での説明:

"The possible suspension points in your code marked with await indicate that the current piece of code might pause execution while waiting for the asynchronous function or method to return. This is also called yielding the thread because, behind the scenes, Swift suspends the execution of your code on the current thread and runs some other code on that thread instead."

重要な特性:

  • "suspension is never implicit or preemptive" - 暗黙的・プリエンプティブな中断はない
  • "every possible suspension point is marked with await"

日本語での定義:
Suspension point とは、非同期関数の実行においてスレッドを手放さなければならない地点である。await でマークされ、コードが実行を一時停止し、そのスレッドで別のコードが実行される可能性がある。中断は暗黙的でもプリエンプティブでもなく、すべての suspension point は await でマークされる。


await

項目 内容
公式定義(英) "The await has no additional semantics; like try, it merely marks that an asynchronous call is being made."
出典 SE-0296: Async/await

The Swift Programming Language での説明:

"You write await in front of the call to mark the possible suspension point. This is like writing try when calling a throwing function, to mark the possible change to the program's flow if there's an error."

日本語での定義:
await とは、非同期呼び出しが行われていることをマークするキーワードである。try と同様に追加のセマンティクスはなく、単に suspension point の可能性を示す。


async function

項目 内容
公式定義(英) "Function types can be marked explicitly as async, indicating that the function is asynchronous."
出典 SE-0296: Async/await

The Swift Programming Language での説明:

"An asynchronous function or asynchronous method is a special kind of function or method that can be suspended while it's partway through execution. This is in contrast to ordinary, synchronous functions and methods, which either run to completion, throw an error, or never return."

日本語での定義:
async function(非同期関数)とは、実行途中で中断(suspend)できる特別な関数である。通常の同期関数が完了まで実行されるか、エラーをスローするか、リターンしないかのいずれかであるのに対し、非同期関数は途中で一時停止できる。


Resume

項目 内容
公式定義(英) "When control returns to an asynchronous function, it picks up exactly where it was."
Continuation での Resume "Note that resume immediately returns control to the caller after transitioning the task out of its suspended state; the task itself does not actually resume execution until its executor reschedules it."
出典 SE-0296, SE-0300

日本語での定義:
Resume とは、中断された非同期関数に制御が戻り、中断された地点から正確に再開することである。Continuation の resume メソッドは Task を中断状態から遷移させた後すぐに呼び出し元に制御を返すが、Task 自体は Executor が再スケジュールするまで実際には実行を再開しない。


Continuation

項目 内容
公式定義(英) "Asynchronous tasks can suspend themselves on continuations which synchronous code can then capture and invoke to resume the task in response to an event."
API withCheckedContinuation, withUnsafeContinuation
メソッド resume(returning:), resume(throwing:), resume(with:)
重要な制約 "exactly one resume method must be called exactly-once on every execution path through the program."
出典 SE-0300: Continuations for interfacing async tasks with synchronous code

日本語での定義:
Continuation とは、非同期タスクが自身を中断するためのオブジェクトであり、同期コードがこれをキャプチャしてイベントに応じてタスクを再開するために呼び出すことができる。resume メソッドはプログラムのすべての実行パスで正確に1回だけ呼び出されなければならない。


Yield

"Yield" は Swift Concurrency において複数の文脈で使用される用語です。それぞれ異なる意味を持つため、混同しないよう注意が必要です。

文脈1: スレッドの譲渡(一般的な概念)

項目 内容
公式説明(英) "This is also called yielding the thread because, behind the scenes, Swift suspends the execution of your code on the current thread and runs some other code on that thread instead."
出典 The Swift Programming Language - Concurrency

説明:
await でマークされた suspension point でコードが中断される際、その動作を "yielding the thread"(スレッドを譲る)と呼ぶ。現在のスレッドでのコード実行を一時停止し、そのスレッドで別のコードが実行される。


文脈2: Task.yield()

項目 内容
公式定義(英) "Suspends the current task and allows other tasks to execute."
用途 長時間実行される操作で、自然な suspension point がない場合に、他の Task に実行機会を与える
重要な注意 "If this task is the highest-priority task in the system, the executor immediately resumes execution of the same task."
出典 Apple Developer Documentation - Task.yield()

日本語での定義:
Task.yield() とは、現在の Task を中断し、他の Task が実行される機会を提供する静的メソッドである。長時間実行されるループ処理など、自然な suspension point がない操作において、他の Task に実行機会を明示的に譲るために使用する。ただし、現在の Task がシステム内で最も優先度の高い Task である場合、Executor は即座に同じ Task の実行を再開するため、常に他の Task に機会が渡るわけではない。

使用例:

for i in 0..<1_000_000 {
    // 重い計算処理
    expensiveComputation(i)

    // 定期的に他のタスクに実行機会を譲る
    if i % 1000 == 0 {
        await Task.yield()
    }
}

Task.sleep() との違い:

  • Task.sleep(): 指定した時間だけ確実に中断する。キャンセル可能
  • Task.yield(): 中断時間は不定。最高優先度の場合は即座に再開される。キャンセル不可

文脈3: AsyncStream.Continuation.yield()

項目 内容
公式定義(英) "Resume the task awaiting the next iteration point by having it return normally from its suspension point. Buffer the value if nothing is awaiting the iterator."
戻り値 YieldResult 列挙型
出典 SE-0314: AsyncStream and AsyncThrowingStream

YieldResult の種類:

値 意味
enqueued(remaining:) 値が正常にバッファに追加された、または待機中のイテレータに即座に消費された。remaining はバッファの残りスロット数
dropped(Element) バッファが満杯のため、値がバッファに追加されずに破棄された
terminated ストリームが既に終了状態(finish() 済みまたはキャンセル済み)のときに値を送出しようとした

日本語での定義:
AsyncStream.Continuation.yield(_:) とは、AsyncStream に値を送出するメソッドである。イテレータを待機している Task があればその Task を再開させ、待機中の Task がなければ値をバッファに格納する。戻り値の YieldResult により、値がエンキューされたか、ドロップされたか、ストリームが終了済みかを判定できる。

使用例:

let stream = AsyncStream<Int> { continuation in
    for i in 1...5 {
        let result = continuation.yield(i)
        switch result {
        case .enqueued(let remaining):
            print("Enqueued, remaining buffer: \(remaining)")
        case .dropped(let value):
            print("Dropped: \(value)")
        case .terminated:
            print("Stream already terminated")
            return
        @unknown default:
            break
        }
    }
    continuation.finish()
}

まとめ: Yield の使い分け

文脈 メソッド/概念 目的
スレッドの譲渡 await による suspension 非同期処理の中断時にスレッドを解放
Task.yield() await Task.yield() 長時間処理で他の Task に明示的に実行機会を譲る
AsyncStream.yield() continuation.yield(value) AsyncStream に値を送出する

Executor

項目 内容
公式定義(英) "A service that can execute jobs."
役割 concurrency runtime が enqueue(_:) を使用して作業をスケジュール
出典 SE-0392: Custom Actor Executors

日本語での定義:
Executor とは、ジョブを実行できるサービスである。並行処理ランタイムが enqueue(_:) を使用して作業をスケジュールする。


SerialExecutor

項目 内容
公式定義(英) "A service that executes jobs one-by-one, and specifically, guarantees mutual exclusion between job executions."
特性 "do not, in general, guarantee specific run-order of jobs, and are free to re-order them."
出典 SE-0392: Custom Actor Executors

日本語での定義:
SerialExecutor とは、ジョブを1つずつ実行し、ジョブ実行間の相互排除を保証するサービスである。ただし、ジョブの特定の実行順序は一般的に保証せず、自由に並べ替えることができる。


6. 安全性・データ競合関連

Data Race

項目 内容
The Swift Programming Language での説明 "A common problem in concurrent code happens when multiple pieces of code try to access some piece of shared mutable state — this is known as a data race."
一般的な定義 複数のスレッドが同時に同じメモリ位置にアクセスし、少なくとも1つが書き込みを行う状況
Swift の対応 "Swift detects and prevents data races, and most data races produce a compile-time error."
出典 The Swift Programming Language - Concurrency

日本語での定義:
Data race とは、複数のコードが共有された mutable state に同時にアクセスしようとするときに発生する並行処理コードの一般的な問題である。Swift はデータ競合を検出・防止し、ほとんどのデータ競合はコンパイル時エラーとなる。


Data Isolation

項目 内容
The Swift Programming Language での説明 "Whenever you read or modify a piece of data, Swift ensures that no other code is modifying it concurrently. This guarantee is called data isolation."
3つの方法 1. Immutable data, 2. 現在の task のみが参照するデータ, 3. Actor によって保護されたデータ
出典 The Swift Programming Language - Concurrency

日本語での定義:
Data isolation とは、データを読み書きする際に、他のコードが同時にそのデータを変更していないことを Swift が保証することである。データを分離する方法は3つある:(1)イミュータブルなデータ、(2)現在の Task のみが参照するデータ、(3)Actor によって保護されたデータ。


7. 混同されやすいペア

nonisolated vs non-Sendable

観点 nonisolated non-Sendable
対象 宣言(関数、プロパティ) 型
意味 Actor の isolation domain から外れている Sendable protocol に準拠していない
制約 nonisolated な宣言で使う型は Sendable でなければならない isolation boundary を越えて渡せない
関係 nonisolated な宣言は Sendable な型のみ扱える non-Sendable な型は nonisolated 宣言で直接使えない

Task vs Thread

観点 Task Thread
レベル 言語レベルの抽象 OS レベルのリソース
スケジューリング 協調的(Suspension Point で明示) プリエンプティブ(OS が制御)

SE-0304:

"a task is to asynchronous functions, what a thread is to synchronous functions"
(Task と非同期関数の関係は、Thread と同期関数の関係に相当する)

The Swift Programming Language:

"The concurrency model in Swift is built on top of threads, but you don't interact with them directly."
(Swift の並行処理モデルはスレッドの上に構築されているが、開発者はスレッドを直接操作しない)


Suspension vs Blocking

観点 Suspension Blocking
スレッドの状態 解放される(他の作業に使える) 占有し続ける
明示性 await で明示 暗黙的に発生しうる

The Swift Programming Language:

"An asynchronous function in Swift can give up the thread that it's running on, which lets another asynchronous function run on that thread while the first function is blocked."
(Swift の非同期関数は実行中のスレッドを手放すことができ、最初の関数がブロックされている間、そのスレッドで別の非同期関数を実行できる)


async vs concurrent

観点 async(非同期) concurrent(並行)
意味 処理を中断・再開できる 複数の処理が同時に進行する
関係 concurrent を実現する手段の一つ async によって実現される

The Swift Programming Language:

"Asynchronous code can be suspended and resumed later, although only one piece of the program executes at a time."
(非同期コードは後で中断・再開できるが、一度にプログラムの1つの部分だけが実行される)

"Parallel code means multiple pieces of code run simultaneously"
(並列コードは複数のコードが同時に実行されることを意味する)


MainActor vs main thread

観点 MainActor main thread
レベル 言語レベルの抽象(Global Actor) OS レベルのリソース
役割 メインスレッドに関連付けられた状態と操作を Actor モデルで保護 アプリケーションのメインとなるスレッド

The Swift Programming Language:

"The main actor is closely related to the main thread, but they're not the same thing."
(main actor と main thread は密接に関連しているが、同一ではない)

SE-0316:

"The main actor is a global actor that describes the main thread."
(main actor はメインスレッドを表す global actor である)


Sendable vs sending

観点 Sendable sending
レベル 型レベルの制約(protocol) 値レベルの制約(parameter/result 修飾子)
意味 型自体が concurrency domain 間で安全に共有可能 値が disconnected region にあり、送信可能な状態
適用対象 型全体 特定のパラメータや戻り値
non-Sendable との関係 non-Sendable 型は境界を越えられない non-Sendable でも sending なら越えられる(所有権移転)
出典 SE-0302 SE-0430

8. Swift固有ではない一般的な用語について

以下の用語は、Swift固有の概念ではなく一般的なコンピュータサイエンスの用語であるため、Swift公式ドキュメントでは明確に定義されていません。参考として一般的な定義を記載します。

Race Condition

項目 内容
一般的な定義 プログラムの動作が複数スレッドやプロセスの相対的なタイミングや実行順序に依存する状態
Swift での扱い Data Race との区別が明示されていない
Data Race との関係 Data Race は Race Condition の一種。Data Race がなくても Race Condition は発生しうる(Data Race については本記事6章を参照)
参考 Race condition - Wikipedia

Thread Safety

項目 内容
一般的な定義 複数のスレッドから同時にアクセスされても、予期しない動作、Race Condition、データ破損を引き起こさないこと
Swift での扱い Swift Concurrency では Thread を直接扱わず、Actor と Task を抽象として使用する。そのため "Thread Safety" という用語はあまり使われず、代わりに Data Race Safety(Data Race の防止)や Data Isolation(データ分離)という概念で安全性を表現する
参考 Thread safety - Wikipedia

Memory Safety

項目 内容
一般的な定義 バッファオーバーフロー、ダングリングポインタ、use-after-free などのメモリアクセスに関するバグや脆弱性から保護されている状態
Swift での扱い Swift は memory-safe な言語として設計されている。The Swift Programming Language には Concurrency とは別に「Memory Safety」章があり、シングルスレッドでの同一メモリへの重複アクセス(in-out パラメータの競合など)を防ぐ仕組みを説明している。Concurrency における Data Race Safety とは異なる概念
参考 Memory safety - Wikipedia、The Swift Programming Language - Memory Safety

9. まとめ

Swift Concurrencyの用語を正確に理解することで、コンパイラのエラーメッセージの意味がより明確になり、適切な解決策を見つけやすくなります。本記事が皆さんの学習の参考になれば幸いです。


参考リンク

Swift Evolution Proposals

その他公式ソース

その他

Discussion