Swift 6의 주요 동시성 안전 규칙

Swift 6는 컴파일 타임에 데이터 레이스를 완전히 방지하는 혁신적인 동시성 안전 시스템을 도입했습니다. 이는 단순한 언어 기능 추가가 아닌, 동시성 프로그래밍의 근본적인 패러다임 변화를 의미합니다[1][2].

핵심 원칙: 컴파일 타임 데이터 레이스 방지

Swift 6의 가장 중요한 특징은 데이터 레이스 안전성을 기본값으로 제공한다는 점입니다[1]. 새로운 Swift 6 언어 모드는 앱의 모든 데이터 레이스 문제를 컴파일 타임 오류로 변환하여, 런타임 전에 동시성 문제를 발견할 수 있게 합니다[1].

Swift의 동시성 시스템은 컴파일러가 모든 가변 상태의 안전성을 이해하고 검증할 수 있도록 하며, 이는 데이터 격리(data isolation)라는 메커니즘을 통해 수행됩니다[3].

주요 동시성 안전 규칙

1. 엄격한 동시성 검사 (Strict Concurrency Checking)

Swift 6는 세 가지 수준의 동시성 검사를 제공합니다[4]:

  • Minimal: 명시적으로 채택된 곳에서만 Sendable 제약 조건을 적용하고, 동시성을 채택한 코드에 대해 액터 격리 검사를 수행
  • Targeted: 액터 격리 검사를 수행하고 명시적으로 채택된 코드에 Sendable 제약 조건을 적용
  • Complete: 전체 데이터 격리를 완전히 적용하며, 컴파일러가 작업과 액터 간의 상태 공유를 방지

2. Sendable 프로토콜 강화

Sendable 프로토콜은 타입이 동시성 도메인 간에 안전하게 전달될 수 있음을 나타내는 마커 프로토콜입니다[5][6]. Swift 6에서는 Sendable 준수가 더욱 엄격해졌습니다:

  • 동시성 도메인 간에 데이터를 전달하려는 모든 시도를 컴파일러가 거부합니다[6]
  • @Sendable 클로저는 캡처된 모든 값이 Sendable이어야 하며, 동기화되지 않은 공유 상태를 수정할 수 없습니다[5]
  • 잘못된 Sendable 준수는 프로그램에 버그를 도입할 수 있으므로 컴파일러가 준수를 검사합니다[6]

3. 액터 격리 규칙 강화

isolated 키워드

isolated 키워드는 함수 매개변수에만 사용할 수 있으며, 해당 함수가 액터의 상태에 await 없이 접근할 수 있게 합니다[7][8]. 이는 불필요한 중단 지점을 줄이고 성능을 최적화합니다[8]:

// isolated 매개변수를 사용하여 전체 메서드를 액터에 격리
static func charge(amount: Double, from bankAccount: isolated BankAccount) async throws -> Double {
    try bankAccount.withdraw(amount: amount)  // await 불필요
    let newBalance = bankAccount.balance      // await 불필요
    return newBalance
}

nonisolated 키워드

nonisolated 키워드는 액터의 가변 상태에 의존하지 않는 속성과 메서드를 표시하여 액터 격리에서 제외시킵니다[7][8]. 이는 특히 델리게이트 메서드나 프로토콜 준수에서 유용합니다[9].

nonisolated(unsafe) 키워드

nonisolated(unsafe) 키워드는 개발자가 스레드 안전성에 대한 책임을 지고 액터 격리를 무시할 수 있게 합니다[2][9]. 이는 기존 코드와의 호환성을 위한 임시적 해결책으로 사용됩니다.

4. 글로벌 액터 시스템

Swift 6에서는 글로벌 액터를 통해 전역 상태와 함수가 액터 격리의 혜택을 받을 수 있습니다[10][11]:

  • 전역 변수의 데이터 레이스를 제거합니다[10]
  • 메인 스레드나 UI 스레드에서만 실행되어야 하는 코드를 모델링합니다[11]
  • @MainActor는 UI 관련 코드의 메인 스레드 실행을 자동화합니다[12]

5. 기본 액터 격리 (Default Actor Isolation)

Swift 6.2에서는 기본 액터 격리가 도입되어, 명시적으로 표시하지 않는 한 코드가 기본적으로 @MainActor에서 실행됩니다[13]. 이는 특히 UI 개발에서 유용하며, 대부분의 UI 관련 코드가 메인 스레드에서 실행되어야 한다는 사실과 일치합니다[13].

점진적 마이그레이션 지원

Swift 6의 데이터 레이스 안전성은 점진적 마이그레이션을 위해 설계되었습니다[14]:

모듈별 마이그레이션

  • 프로젝트의 데이터 레이스 안전 문제를 모듈별로 해결할 수 있습니다[14]
  • Swift 5 언어 모드에서 경고로 액터 격리와 Sendable 검사를 활성화하여 진행 상황을 평가할 수 있습니다[14]

컴파일러 플래그 설정

다양한 방법으로 엄격한 동시성 검사를 활성화할 수 있습니다[14]:

  • Swift 컴파일러: -strict-concurrency=complete
  • SwiftPM: .enableUpcomingFeature("StrictConcurrency")
  • Xcode: SWIFT_STRICT_CONCURRENCY = complete

마이그레이션 전략

Apple은 기존 프로젝트를 Swift 6로 마이그레이션하기 위한 구체적인 가이드라인을 제공합니다[15]:

  1. 모듈별 순차 마이그레이션: 다른 모듈에 덜 의존하는 모듈부터 시작
  2. 우선순위 설정: 안전하지 않은 전역 상태나 간단한 Sendable 타입을 포함한 모듈을 우선적으로 처리
  3. 세분화된 컴파일러 스위치 사용: 특정 유형의 문제를 점진적으로 해결

동시성 안전성의 3단계 접근법

Swift 6.2 비전 문서에서는 동시성에 대한 점진적 공개 경로를 제시합니다[16]:

  • 1단계: 단순하고 단일 스레드 코드 작성 (병렬성 없음, 데이터 레이스 없음)
  • 2단계: 데이터 레이스 안전 오류 없이 비동기 코드 작성 (async/await 사용)
  • 3단계: 병렬성으로 성능 향상 (구조화된 동시성과 고급 기능 활용)

이러한 단계적 접근법은 개발자가 Swift 동시성을 천천히 채택할 수 있도록 언어를 개선하는 데 중점을 둡니다[16].

Swift 6의 동시성 안전 규칙은 단순히 컴파일러 검사를 강화하는 것을 넘어서, 동시성 프로그래밍을 근본적으로 더 안전하고 접근하기 쉽게 만드는 포괄적인 시스템을 구축했습니다. 이는 런타임 크래시를 줄이고 개발자가 수동으로 데이터 레이스를 추적하고 방지해야 하는 부담을 크게 줄여줍니다[2].

출처
[1] what changes prevent data races in swift version 6 | Ask WWDC https://askwwdc.com/q/1783
[2] Data Race Safety Swift 6 https://www.swiftlab.fr/data-race-safety-swift-6/
[3] Data Race Safety | Documentation – Swift.org https://www.swift.org/migration/documentation/swift-6-concurrency-migration-guide/dataracesafety/
[4] Enable Swift 6 Features & Concurrency in Xcode 16 https://swiftpublished.com/article/strict-concurrency-in-swift-6-part-2
[5] Understanding Sendable in Swift – Wesley de Groot https://wesleydegroot.nl/blog/Sendable-in-Swift
[6] Sendable WTF? https://sendable.wtf
[7] Swift actor isolated vs nonisolated https://byby.dev/swift-actor-isolation
[8] Nonisolated and isolated keywords: Understanding Actor isolation https://www.avanderlee.com/swift/nonisolated-isolated/
[9] [Swift Concurrency] Swift 6로 마이그레이션하기 – velog https://velog.io/@jeunghun2/Migrate-to-Swift-63-Xcode-%EC%97%90%EB%9F%AC-%ED%95%B4%EA%B2%B0
[10] swift-evolution/proposals/0316-global-actors.md at main – GitHub https://github.com/apple/swift-evolution/blob/main/proposals/0316-global-actors.md
[11] Exodai Academy – Learn, Code, and Create! https://exodai.academy/guide/concurrency-in-swift/global-actors-in-swift
[12] Post navigation https://blog.hobbyistsoftware.com/2022/11/mainactor-the-rules/
[13] Default Actor Isolation in Swift 6.2 – SwiftLee https://www.avanderlee.com/concurrency/default-actor-isolation-in-swift-6-2/
[14] Swift.org https://www.swift.org/documentation/concurrency/
[15] Swift 6 Brings New Opt-In Data-Race Safe Mode – InfoQ https://www.infoq.com/news/2024/06/swift-6-data-race-safety-mode/
[16] Swift 6.2: A first look at how it’s changing Concurrency – SwiftLee https://www.avanderlee.com/concurrency/swift-6-2-concurrency-changes/
[17] Concurrency in Swift 5 and 6 – Discussion https://forums.swift.org/t/concurrency-in-swift-5-and-6/49337
[18] Change to Global Actor Inference in Swift 6 Language Mode? https://forums.swift.org/t/change-to-global-actor-inference-in-swift-6-language-mode/76086
[19] No More Singletons: Why Swift 6 Encourages the Shift to Actors for … https://www.linkedin.com/pulse/more-singletons-why-swift-6-encourages-shift-actors-safer-goudarzi-wqszf
[20] swift-evolution/proposals/0431-isolated-any-functions.md at main https://github.com/apple/swift-evolution/blob/main/proposals/0431-isolated-any-functions.md
[21] Is there a way to use Swift 6 without … https://forums.swift.org/t/is-there-a-way-to-use-swift-6-without-swift-strict-concurrency-complete/74677
[22] Swift 6 strict concurrency : r/swift – Reddit https://www.reddit.com/r/swift/comments/1icj54z/swift_6_strict_concurrency/
[23] Strict Concurrency Checking in Swift Packages https://useyourloaf.com/blog/strict-concurrency-checking-in-swift-packages/
[24] nonisolated(unsafe) properties redundant for stored properties https://forums.swift.org/t/nonisolated-unsafe-properties-redundant-for-stored-properties/70895
[25] Adopting strict concurrency in Swift 6 apps – Apple Developer https://developer.apple.com/documentation/swift/adoptingswift6
[26] GlobalActor | Apple Developer Documentation https://developer.apple.com/documentation/swift/globalactor

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다