포스트

[WWDC22] Eliminate data races using Swift Concurrency

이 글은 WWDC 세션의 transcript 와 영상 화면을 Claude Code 로 정리한 글이고, 실제로 쓴 날은 2026-11-24 다. code 는 세션 page 의 snippet 에 빠진 선언을 채워 Xcode 27.0 (Swift 6.4) 의 iOS 27 Simulator SDK 로 compile 검사를 했다.


세션 정보


한 줄 요약

Swift Concurrency 는 기능의 모음이기 전에 data race 가 없는 program 을 만드는 구조다. task 와 actor 가 각자의 isolation domain 을 이루고, 그 경계를 넘는 값은 Sendable 이어야 한다는 규칙을 compiler 가 검사한다. 이 검사는 build setting 으로 Minimal, Targeted, Complete 세 단계에 걸쳐 조금씩 켤 수 있다.


세션의 구성

세션은 Swift Concurrency 를 하나씩 소개하는 대신 전체를 하나의 그림으로 다시 본다. async/await, structured concurrency, actor 는 서로 관련된 언어 기능이지만, 그 밑에는 data race 없이 동시성 program 을 짜는 하나의 model 이 있다는 것이 출발점이다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

Doug 는 이 model 을 바다에 빗대어 설명한다. task 는 바다를 돌아다니는 배고, actor 는 섬이고, compiler 는 배와 섬 사이를 오가는 화물을 검사하는 세관원이다. 세션 내내 이 비유가 이어지고 예제 code 의 type 이름도 pineapple, chicken, island 로 되어 있다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

순서내용발표
1task isolation 과 SendableDoug
2actor isolation, main actorDoug
3atomicityDoug
4orderingDoug
5strict concurrency checking 의 단계적 도입Doug

화면의 목차에는 앞의 네 가지만 있고, 다섯 번째는 세션 끝부분에 따로 이어진다. 이 계보의 앞선 세션인 Meet async/await in Swift, Protect mutable state with Swift actors, Swift concurrency: Behind the scenes 를 먼저 읽으면 이 글의 용어가 덜 낯설다.


task isolation

첫 번째 장은 task 다. 배 한 척이 맡은 일을 처음부터 끝까지 혼자 해내는 모습으로 task 를 설명하고, 배끼리 물건을 주고받을 때 무엇이 안전하고 무엇이 위험한지를 따진다. 여기서 Sendable 이 나온다.


task 의 세 가지 성질

task 는 특정한 일 하나를 처음부터 끝까지 수행한다. 세션은 task 의 성질을 셋으로 정리한다.

  • sequential: task 안의 code 는 위에서 아래로 순서대로 실행된다.
  • asynchronous: await 지점에서 몇 번이고 멈췄다가 다시 이어질 수 있다.
  • self-contained: 자기 자원을 가지고 다른 task 와 독립적으로 움직인다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

1
2
3
4
5
6
7
func startDinner() {
  Task.detached {
    let fish = await catchFish()
    let dinner = await cook(fish)
    await eat(dinner)
  }
}

세션의 snippet 은 Task.detached { } 만 있다. startDinner() 로 감싸고 Fish, Dinner, catchFish(), cook(_:), eat(_:) 를 빈 body 로 채웠다. Swift 5 mode 의 세 단계와 Swift 6 mode 에서 모두 진단 없이 통과했다.

Task.detached

detached(name:priority:operation:) 은 호출한 곳의 actor isolation 과 priority 를 물려받지 않는 독립된 task 를 만드는 static method 다. 2022년 세션 화면의 선언에는 name parameter 가 없고 operation 이 @Sendable 이었는데, 지금 문서의 선언은 name 이 추가되고 operation 이 sending 으로 바뀌어 있다.

배들이 서로 완전히 독립적이면 data race 는 생길 수 없다. 하지만 서로 아무것도 주고받지 못하는 task 는 쓸모가 적다. 문제는 주고받는 방식이다.


value type 의 전달

한 배가 다른 배에 pineapple 을 건넨다고 하자. pineapple 은 struct 다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

1
2
3
4
5
6
7
8
9
10
11
12
13
enum Ripeness {
  case hard
  case perfect
  case mushy(daysPast: Int)
}

struct Pineapple {
  var weight: Double
  var ripeness: Ripeness

  mutating func ripen() async { … }
  mutating func slice() -> Int { … }
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

{ … } 는 세션이 생략한 부분이다. 검사할 때는 ripen() 이 ripeness 를 .perfect 로 바꾸고 slice() 가 1 을 돌려주도록 채웠다. 그리고 뒤에 나오는 $0.ripeness == .perfect 비교가 compile 되도록 Ripeness 에 Equatable 을 붙였다. associated value 가 있는 enum 은 Equatable 을 선언해야 == 가 합성되기 때문이다.

struct 는 value type 이라서 건네는 순간 copy 가 생긴다. 받은 배가 자기 pineapple 을 slice() 하든 준 배가 자기 것을 ripen() 하든 서로에게 영향이 없다. Swift 가 value type 을 권해 온 이유가 여기서도 그대로 통한다.

출처: WWDC22 - Eliminate data races using Swift Concurrency


reference type 의 공유

이번에는 닭을 건넨다. 닭은 class 다.

1
2
3
4
5
6
7
8
final class Chicken {
  let name: String
  var currentHunger: HungerLevel

  func feed() { … }
  func play() { … }
  func produce() -> Egg { … }
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

HungerLevel 과 Egg 는 세션에 선언이 없어 각각 case 둘짜리 enum 과 빈 struct 로 채웠고, initializer 와 method body 도 직접 넣었다.

class 는 reference type 이라서 건네도 copy 가 생기지 않는다. 두 배가 같은 닭 한 마리를 가리키게 된다. 한 배가 feed() 를 부르는 동안 다른 배가 play() 를 부르면 같은 object 의 mutable state 를 동시에 건드리게 되고, 이것이 data race 다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

그래서 pineapple 은 건네도 되고 닭은 건네면 안 된다는 것을 compiler 가 알 수 있어야 한다.


Sendable 이란?

Sendable 은 isolation domain 을 넘어가도 data race 가 생기지 않는 type 을 나타내는 protocol 이다. 요구 사항이 하나도 없는 marker protocol 이고, 어떤 type 이 안전하게 공유될 수 있는지는 conformance 로 표시한다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

1
2
struct Pineapple: Sendable { … } // value type 이라 Sendable 이 될 수 있다
class Chicken: Sendable { }      // 동기화가 없는 reference type 이라 될 수 없다

위 두 줄은 세션이 개념을 보이려고 쓴 조각이라 그대로는 compile 대상이 아니다. 실제 검사 결과는 아래 struct 와 class 항목에 적었다.

Sendable

Sendable 은 값을 다른 concurrency domain 으로 넘겨도 안전한 type 임을 나타내는 protocol 이다.

isolation domain 이라는 말은 이 세션에서 처음 나온다. task 하나, actor 하나가 각각 하나의 isolation domain 이고, 그 안의 state 는 그 domain 안에서만 건드린다. Sendable 은 그 경계를 넘을 수 있는 통행증이다.


task 경계의 Sendable 검사

compiler 는 값이 task 밖으로 나가는 곳마다 Sendable 인지 검사한다. task 가 값을 돌려주는 경우가 대표적이다.

1
2
3
4
5
6
7
8
func adopt() async {
  let petAdoption = Task {
    let chickens = await hatchNewFlock()
    return chickens.randomElement()!
  }
  let pet = await petAdoption.value
  pet.play()
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

세션의 조각을 adopt() 로 감싸고 hatchNewFlock() 을 채웠다. task 가 Chicken 을 결과로 돌려주므로 세션의 말대로 진단이 나온다. 지금 compiler 의 결과는 다음과 같다.

1
2
3
4
Swift 5, minimal   : 진단 없음
Swift 5, targeted  : warning: type 'Chicken' does not conform to the 'Sendable' protocol; this is an error in the Swift 6 language mode
Swift 5, complete  : 같은 warning
Swift 6            : error: type 'Chicken' does not conform to the 'Sendable' protocol

이 제약이 어디서 오는지는 Task 의 선언을 보면 알 수 있다.

1
2
3
4
5
struct Task<Success: Sendable, Failure: Error> {
  var value: Success {
    get async throws { … }
  }
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

위 code 는 표준 라이브러리의 선언을 세션이 줄여서 보여 준 것이라 직접 compile 하지 않았다.

Task

Task 는 비동기 작업의 단위를 나타내는 struct 이고, 결과 type 인 Success 가 Sendable 이어야 한다는 제약을 가지고 있다.

task 가 data 를 주고받을 수 있는 곳에는 어디든 이런 Sendable 제약이 걸려 있다. 세션은 이 검사를 세관원에 빗댄다. 배 사이로 건너가는 화물을 세관원이 하나하나 확인하고, pineapple 은 통과시키고 닭은 막는다.

출처: WWDC22 - Eliminate data races using Swift Concurrency


struct 와 enum 의 Sendable

struct 와 enum 은 안에 든 것이 모두 Sendable 이면 Sendable 이 될 수 있다. Int, Double 같은 기본 type 은 이미 Sendable 이고, Array 나 Dictionary 같은 collection 은 element 가 Sendable 일 때만 Sendable 이 되는 conditional conformance 를 가진다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
enum Ripeness: Sendable {
  case hard
  case perfect
  case mushy(daysPast: Int)
}

struct Pineapple: Sendable {
  var weight: Double
  var ripeness: Ripeness
}

struct Crate: Sendable {
  var pineapples: [Pineapple]
}

이 셋은 Swift 5 mode 의 세 단계와 Swift 6 mode 에서 모두 통과했다. 다른 file 의 type 과 이름이 겹치지 않도록 검사할 때는 Ripeness2, Pineapple2 로 이름을 바꿨다.

닭의 배열을 담은 struct 는 사정이 다르다.

1
2
3
struct Coop: Sendable {
  var flock: [Chicken]
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

세션 화면의 문구는 “has non-sendable type ‘[Chicken]’” 이었고 지금 compiler 의 문구는 조금 다르다.

1
2
Swift 5 (세 단계 모두) : warning: stored property 'flock' of 'Sendable'-conforming struct 'Coop' contains non-Sendable type 'Chicken'; this is an error in the Swift 6 language mode
Swift 6               : error: stored property 'flock' of 'Sendable'-conforming struct 'Coop' contains non-Sendable type 'Chicken'

한 가지 더 있다. public 이 아닌 struct 와 enum 은 조건을 만족하면 compiler 가 Sendable conformance 를 알아서 추론한다. : Sendable 을 쓰지 않은 Pineapple 을 task 사이로 넘겨도 진단이 없는 이유다. public type 은 module 밖에 대한 약속이 되므로 직접 적어야 한다.


class 의 Sendable

class 는 reference type 이라서 조건이 훨씬 좁다. final 이고 저장 property 가 전부 immutable 일 때만 Sendable 이 될 수 있다.

1
2
3
4
final class Chicken: Sendable {
  let name: String
  var currentHunger: HungerLevel
}

currentHunger 가 var 이라서 이 선언은 받아들여지지 않는다. 검사할 때는 SendableChicken 으로 이름을 바꾸고 initializer 를 넣었다.

1
2
Swift 5 (세 단계 모두) : warning: stored property 'currentHunger' of 'Sendable'-conforming class 'SendableChicken' is mutable; this is an error in the Swift 6 language mode
Swift 6               : error: stored property 'currentHunger' of 'Sendable'-conforming class 'SendableChicken' is mutable

lock 처럼 자기 안에서 직접 동기화를 하는 reference type 도 있다. 이런 type 은 개념적으로는 Sendable 이지만 compiler 가 그 사실을 증명할 방법이 없다. 이럴 때 @unchecked Sendable 을 쓴다.

1
2
3
4
class ConcurrentCache<Key: Hashable & Sendable, Value: Sendable>: @unchecked Sendable {
  var lock: NSLock
  var storage: [Key: Value]
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

두 property 에 초기값 (NSLock(), [:]) 을 넣어 검사했고 모든 mode 에서 통과했다.

NSLock

NSLock 은 한 번에 한 thread 만 지나가게 하는 Foundation 의 lock class 다.

@unchecked Sendable 은 compiler 의 검사를 끄고 개발자가 책임지겠다는 표시다. Doug 는 조심해서 쓰라고 강조한다. mutable state 를 @unchecked Sendable 로 몰래 내보내면 Swift 가 주려는 data race 안전 보장이 그 자리에서 무너진다.


task 를 만드는 closure 의 검사

값이 task 경계를 넘는 길은 return 만이 아니다. task 를 만드는 closure 가 바깥 값을 capture 하는 것도 경계를 넘는 일이다.

1
2
3
4
5
6
func feedLily() {
  let lily = Chicken(name: "Lily")
  Task.detached {@Sendable in
    lily.feed()
  }
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

feedLily() 로 감싼 것만 내가 추가했다. 원래 배에 있는 lily 를 새로 띄운 작은 배가 함께 쓰게 되므로 진단이 나온다.

1
2
3
Swift 5, minimal / targeted : 진단 없음
Swift 5, complete           : warning: capture of 'lily' with non-Sendable type 'Chicken' in a '@Sendable' closure; this is an error in the Swift 6 language mode
Swift 6                     : error: capture of 'lily' with non-Sendable type 'Chicken' in a '@Sendable' closure

snippet 의 @Sendable in 은 설명을 위해 드러내 쓴 것이다. 세션 당시에는 쓰지 않아도 task 를 만드는 closure 가 @Sendable closure 로 추론되었다. 그 근거가 Task.detached 의 선언이다.

1
2
3
4
5
6
struct Task<Success: Sendable, Failure: Error> {
  static func detached(
    priority: TaskPriority? = nil,
    operation: @Sendable @escaping () async throws -> Success
  ) -> Task<Success, Failure>
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

이것도 2022년의 표준 라이브러리 선언을 옮긴 것이라 compile 대상이 아니다. 앞에서 적었듯 지금 선언은 operation 이 sending 으로 바뀌었다.

TaskPriority

TaskPriority 는 task 의 우선순위를 나타내는 struct 다.

@Sendable 은 function type 에 붙는 attribute 다. @Sendable closure 는 Sendable 인 값만 capture 할 수 있고, 그래서 그 closure 자체가 Sendable 이 된다. 세션은 tuple 도 element 가 모두 Sendable 이면 Sendable 이라는 점을 덧붙인다.

여기까지가 task isolation 이다. task 는 서로 격리된 채 독립적으로 실행되고, Sendable 검사가 그 격리를 지켜 준다. 값을 공유해야 하는 곳에는 Sendable 제약을 건다.

출처: WWDC22 - Eliminate data races using Swift Concurrency


actor isolation

task 끼리 값을 copy 해서 주고받는 것만으로는 부족하다. 여러 task 가 함께 쓰는 mutable state 가 필요할 때가 있고, 그 자리를 actor 가 맡는다. 비유에서 actor 는 섬이다.


actor 라는 섬

actor 는 mutable state 와 그 state 를 건드리는 code 를 함께 격리한다. 섬에 있는 닭과 pineapple 은 섬 위에서만 만질 수 있다.

1
2
3
4
5
6
actor Island {
  var flock: [Chicken]
  var food: [Pineapple]

  func advanceTime()
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

advanceTime() 에 body 가 없어서 이 조각만으로는 compile 되지 않는다. body 가 있는 전체 형태는 조금 뒤에 나온다.

actor

Actor 는 모든 actor type 이 암묵적으로 따르는 protocol 이고, actor keyword 로 선언한 type 은 자기 mutable state 에 한 번에 한 task 만 접근하게 한다.

섬에는 한 번에 배 한 척만 들어올 수 있다. 다른 배는 차례를 기다린다. 배가 섬에 들어가려고 하는 지점이 await 이고, 거기서 task 는 멈췄다가 자기 차례가 오면 섬 위에서 다시 실행된다.

1
2
3
4
5
func nextRound(islands: [Island]) async {
  for island in islands {
    await island.advanceTime()
  }
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

nextRound(islands:) 는 뒤의 Island 전체 선언과 같은 file 에 넣어 검사했다.


task 와 actor 사이의 Sendable 검사

배와 배 사이처럼 배와 섬 사이에도 세관원이 있다. non-Sendable 값은 task 와 actor 사이를 오갈 수 없다.

1
2
await myIsland.addToFlock(myChicken)
myChicken = await myIsland.adoptPet()

출처: WWDC22 - Eliminate data races using Swift Concurrency

첫 줄은 배의 닭을 섬에 내려놓고, 둘째 줄은 섬의 닭을 배로 데려온다. 세션은 두 줄 모두 허용되지 않는다고 말한다. 어느 쪽이든 같은 Chicken object 를 배와 섬이 함께 가리키게 되기 때문이다.

지금 compiler 는 조금 다르게 판단한다. Island 에 addToFlock(_:) 과 adoptPet() 을 채우고 두 줄을 함수 하나에 넣어 검사했더니 둘째 줄에만 진단이 나왔다.

1
2
3
Swift 5, minimal / targeted : 진단 없음
Swift 5, complete           : warning: non-Sendable 'Chicken'-typed result can not be returned from actor-isolated instance method 'adoptPet()' to nonisolated context; this is an error in the Swift 6 language mode
Swift 6                     : error: 같은 문구

첫 줄이 통과한 것은 Swift 6 에 들어온 region-based isolation 때문으로 보인다. 넘긴 뒤에 보내는 쪽이 그 값을 다시 쓰지 않으면 compiler 가 안전하다고 판단한다. 이 예에서는 myChicken 이 바로 다음 줄에서 다른 값으로 덮어써진다. 확인하려고 넘긴 뒤에 myChicken.play() 를 부르는 변형을 따로 만들었더니 예상대로 진단이 나왔다.

1
2
3
4
5
func exchange(myIsland: Island) async {
  let myChicken = Chicken(name: "Mine")
  await myIsland.addToFlock(myChicken)
  myChicken.play()
}
1
2
Swift 5, complete : warning: sending 'myChicken' risks causing data races; this is an error in the Swift 6 language mode
Swift 6           : error: sending 'myChicken' risks causing data races

세션의 원칙은 그대로다. 달라진 것은 compiler 가 “실제로 공유되는가”를 더 정밀하게 본다는 점이다.


actor reference 의 Sendable

actor 의 state 는 격리되어 있지만 actor 를 가리키는 reference 는 어디로 넘겨도 된다. 섬 자체를 배에 싣는 것이 아니라 섬으로 가는 지도를 건네는 것과 같다. 지도를 가진 배는 섬에 갈 수 있지만, 섬의 state 를 만지려면 여전히 await 로 차례를 기다려야 한다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

그래서 모든 actor type 은 암묵적으로 Sendable 이다. : Sendable 을 적지 않아도 된다.


actor 에 격리되는 code

actor 안에 적혀 있다고 해서 모든 code 가 actor 위에서 도는 것은 아니다. 세션은 advanceTime() 하나를 놓고 줄마다 어디서 실행되는지를 짚는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
actor Island {
  var flock: [Chicken]
  var food: [Pineapple]

  func advanceTime() {
    let totalSlices = food.indices.reduce(0) { (total, nextIndex) in
      total + food[nextIndex].slice()
    }

    Task {
      flock.map(Chicken.produce)
    }

    Task.detached {
      let ripePineapples = await food.filter { $0.ripeness == .perfect }
      print("There are \(ripePineapples.count) ripe pineapples on the island")
    }
  }
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

화면은 줄마다 섬 또는 배 아이콘을 붙여 구분한다. 내용은 이렇다.

  • instance property 인 flock 과 food 는 actor 에 격리된다.
  • instance method 인 advanceTime() 도 기본으로 격리된다.
  • reduce 에 넘긴 closure 는 @Sendable 이 아니다. 그 자리에서 바로 실행되고 밖으로 나가지 않으므로 actor 위에 머문다. 그래서 food[nextIndex].slice() 를 await 없이 부른다.
  • Task { } 는 자기를 만든 context 의 isolation 을 물려받는다. actor 안에서 만들었으니 actor 위에서 실행되고 flock 에 await 없이 접근한다.
  • Task.detached { } 는 물려받지 않는다. actor 밖에서 도는 code 라서 food 를 읽으려면 await 가 필요하다. 이런 code 를 non-isolated code 라고 부른다.

이 code 는 그대로는 지금 compiler 를 통과하지 못했다. property 에 초기값 [] 을 주고, totalSlices 를 print 하고, detached task 안의 food 를 self.food 로 쓴 뒤 돌린 결과다.

1
2
3
4
Swift 5, minimal   : 진단 없음
Swift 5, targeted  : warning: type '() -> Egg' does not conform to the 'Sendable' protocol; this is an error in the Swift 6 language mode
Swift 5, complete  : 같은 warning
Swift 6            : error: type '() -> Egg' does not conform to the 'Sendable' protocol

원인은 flock.map(Chicken.produce) 다. Chicken.produce 는 (Chicken) -> () -> Egg 이라서 map 의 결과가 [Egg] 가 아니라 closure 의 배열이 되고, 그것이 task 의 결과 type 이 되면서 Sendable 제약에 걸린다. 그 줄을 다음처럼 바꾸면 모든 mode 에서 진단 없이 통과했다.

1
2
3
    Task {
      _ = flock.map { $0.produce() }
    }

세션이 보이려던 것은 Task { } 가 actor isolation 을 물려받는다는 점이고, 그 점은 바꾼 code 에서도 똑같이 드러난다.

Task 의 initializer

init(name:priority:operation:) 은 현재 actor 의 isolation 과 priority 를 물려받는 unstructured task 를 만드는 initializer 다.


nonisolated 함수

actor 안의 함수를 일부러 격리 밖으로 꺼낼 수도 있다. nonisolated keyword 를 붙이면 된다.

1
2
3
4
5
6
extension Island {
  nonisolated func meetTheFlock() async {
    let flockNames = await flock.map { $0.name }
    print("Meet our fabulous flock: \(flockNames)")
  }
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

non-isolated async code 는 항상 global cooperative pool 에서 실행된다. 배가 섬을 떠나 바다로 나가는 셈이라 세관원의 검사를 받는다. 이 함수는 flock 을 await 로 읽어 오는데 [Chicken] 은 Sendable 이 아니므로 섬 밖으로 가지고 나갈 수 없다. 세션은 이 code 가 error 라고 말하고, 지금 compiler 도 같은 판단을 한다.

1
2
3
4
Swift 5, minimal   : 진단 없음
Swift 5, targeted  : warning: non-Sendable type '[Chicken]' of property 'flock' cannot exit actor-isolated context; this is an error in the Swift 6 language mode
Swift 5, complete  : 같은 warning
Swift 6            : error: non-Sendable type '[Chicken]' of property 'flock' cannot exit actor-isolated context

global cooperative pool 이 무엇인지는 Swift concurrency: Behind the scenes 에 정리해 두었다. 한 가지 짚어 둘 점이 있다. non-isolated async 함수가 항상 pool 에서 실행된다는 것은 2022년 기준의 설명이고, 이후 Swift 에는 호출한 쪽의 isolation 에서 실행하게 하는 선택지가 추가되었다. 이 글에서는 세션의 설명을 따른다.


호출한 곳을 따르는 sync code

non-isolated 이면서 sync 인 code 는 다르게 움직인다. 자기 자리가 따로 없고 부른 쪽의 isolation 에서 그대로 실행된다.

1
2
3
4
5
6
7
8
9
func greet(_ friend: Chicken) { }

extension Island {
  func greetOne() {
    if let friend = flock.randomElement() {
      greet(friend)
    }
  }
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

greet(_:) 는 actor 와 상관없는 전역 함수다. actor 에 격리된 greetOne() 이 부르면 greet(_:) 도 actor 위에서 실행된다. 섬 위에서 일어나는 일이므로 Chicken 을 넘겨도 문제가 없다.

1
2
3
4
5
func greetAny(flock: [Chicken]) async {
  if let friend = flock.randomElement() {
    greet(friend)
  }
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

같은 greet(_:) 를 non-isolated async 함수인 greetAny(flock:) 가 부르면 이번에는 cooperative pool 에서 실행된다. greetOne() 과 greetAny(flock:) 는 Island 선언과 같은 file 에 넣어 검사했고 둘 다 진단이 없었다.

actor isolation 을 정리하면 네 가지다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

  • actor instance 하나하나는 program 의 나머지와 격리된다.
  • actor 위에서는 한 번에 한 task 만 실행된다.
  • actor 에 들어가거나 나올 때마다 Sendable 검사가 일어난다.
  • actor 자체는 Sendable 이다.

main actor

actor 가운데 특별한 것이 하나 있다. main actor 다. 비유에서는 바다 한가운데 있는 큰 섬이고, UI 를 그리고 사용자 입력을 받는 main thread 를 대표한다.

출처: WWDC22 - Eliminate data races using Swift Concurrency


main actor 의 성질

main actor 는 크지만 그래도 actor 다. UI 와 관련된 state 가 잔뜩 있고 UI framework 와 앱의 code 가운데 상당수가 여기서 돌아야 하지만, 한 번에 처리하는 일은 여전히 하나다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

그래서 main actor 위에서 오래 걸리는 일을 하면 다른 배들이 줄지어 기다리게 되고 UI 가 멈춘다. 긴 계산은 main actor 밖에서 하고 결과만 가지고 돌아와야 한다.


함수와 closure 의 격리

main actor 에 격리하려면 @MainActor attribute 를 쓴다. 함수에도, closure 에도 붙일 수 있다.

1
2
3
4
5
6
7
8
9
10
11
@MainActor func updateView() { … }

Task { @MainActor in
  // …
  view.selectedChicken = lily
}

nonisolated func computeAndUpdate() async {
  computeNewValues()
  await updateView()
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

updateView() 는 main actor 에서만 실행되고, Task { @MainActor in } 은 task 의 body 를 main actor 에서 돌린다. computeAndUpdate() 는 non-isolated async 함수라서 계산은 cooperative pool 에서 하고, await updateView() 에서 main actor 로 건너간다.

검사할 때는 selectedChicken property 를 가진 @MainActor final class FlockView 와 전역 view, 빈 computeNewValues() 를 채웠고, Task 조각은 lily 를 만드는 @MainActor 함수 안에 넣었다. 모든 mode 에서 진단이 없었다. lily 는 Sendable 이 아니지만 이미 main actor 위에 있는 함수에서 같은 main actor 로 넘기는 것이라 경계를 넘지 않는다.

MainActor

MainActor 는 main thread 에서 실행되는 singleton actor 이고, attribute 로 붙이면 그 선언을 main actor 에 격리한다.


main actor type

type 전체에 @MainActor 를 붙일 수도 있다. 그러면 그 type 의 property 와 method 가 모두 main actor 에 격리된다.

1
2
3
4
5
6
7
8
9
10
11
@MainActor
class ChickenValley: Sendable {
  var flock: [Chicken]
  var food: [Pineapple]

  func advanceTime() {
    for chicken in flock {
      chicken.eat(from: &food)
    }
  }
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

var 로 선언한 저장 property 가 있고 final 도 아닌데 Sendable 이 붙어 있다. 앞에서 본 class 의 조건과 어긋나 보이지만 이유가 있다. state 가 전부 main actor 에 격리되어 있으므로 reference 를 어디로 넘기든 state 를 만지려면 main actor 를 거쳐야 한다. 일반 actor 의 reference 가 Sendable 인 것과 같은 이치다. 실제로 main actor 에 격리된 class 는 : Sendable 을 쓰지 않아도 암묵적으로 Sendable 이다.

property 에 초기값 [] 을 주고 Chicken 에 eat(from:) 을 채워 검사했다. 모든 mode 에서 통과했다.

UI 의 view 와 view controller 는 이런 식으로 main actor 에 격리되어 있어서, 자기들끼리는 await 없이 state 를 주고받고 밖에서는 reference 를 자유롭게 들고 다닐 수 있다.


앱의 구조

이 조각들을 모으면 앱의 구조가 그려진다. view 와 view controller 는 main actor 라는 큰 섬에 있다. 나머지 logic 은 다른 actor 들이 각자의 state 를 지키고, task 들이 그 사이를 오가며 일을 나른다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

배가 너무 많거나 한 섬에 몰리면 느려진다. 그런 문제를 찾는 방법은 같은 해의 Visualize and optimize Swift concurrency 세션이 다룬다고 Doug 는 안내한다.


atomicity

지금까지의 규칙은 low-level data race, 곧 같은 memory 를 동시에 건드려 data 가 깨지는 일을 없앤다. 하지만 그것만으로 program 이 옳아지지는 않는다. 더 높은 수준의 문제인 atomicity 는 여전히 개발자의 몫이다.


await 사이의 틈

actor 는 한 번에 한 task 만 실행한다. 그런데 task 가 actor 위에서 실행을 멈추면 actor 는 다른 task 를 받아들인다. 섬에서 배가 떠나면 다른 배가 들어올 수 있다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

세션의 예는 섬에 pineapple 을 내려놓는 함수다.

1
2
3
4
5
func deposit(pineapples: [Pineapple], onto island: Island) async {
   var food = await island.food
   food += pineapples
   await island.food = food
}

이 함수는 actor 밖에 있는 non-isolated async code 다. 배가 섬에 가서 food 의 copy 를 받아 온다. 섬에 pineapple 이 둘 있었다고 하자.

출처: WWDC22 - Eliminate data races using Swift Concurrency

배로 돌아와 자기가 가진 pineapple 셋을 더한다. 이제 배 위의 배열에는 다섯 개가 있다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

다시 섬에 가서 섬의 food 를 그 다섯 개짜리 배열로 덮어쓴다. 아무도 끼어들지 않으면 결과는 옳다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

문제는 두 await 사이다. 배가 바다에 나와 있는 동안 해적선이 섬에 들러 pineapple 을 전부 가져갈 수 있다.

1
await island.food.takeAll()

출처: WWDC22 - Eliminate data races using Swift Concurrency

원래 배는 그 사실을 모른 채 돌아와 다섯 개를 내려놓는다. 섬에는 셋이 있어야 하는데 다섯이 생긴다. 해적이 가져간 둘이 다시 나타난 것이다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

memory 가 깨진 것은 아니다. 각 접근은 actor 가 지켜 주었다. 깨진 것은 “읽고, 더하고, 쓴다”는 한 묶음의 논리다. takeAll() 은 세션이 상황을 설명하려고 든 한 줄이라 검사 대상에 넣지 않았다.


compiler 의 거부와 sync method

다행히 compiler 가 이 code 를 받아 주지 않는다. actor 밖에서 actor 의 state 를 직접 바꾸는 것은 허용되지 않는다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

지금 compiler 의 진단은 이렇다. Swift 5 mode 의 minimal 단계에서도 error 다.

1
2
error: actor-isolated property 'food' can not be mutated from a nonisolated context
warning: no 'async' operations occur within 'await' expression

고치는 방법은 이 일을 actor 의 sync method 로 옮기는 것이다.

1
2
3
4
5
6
7
extension Island {
   func deposit(pineapples: [Pineapple]) {
      var food = self.food
      food += pineapples
      self.food = food
   }
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

sync code 는 중간에 끊기지 않는다. 이 method 가 실행되는 동안 배는 섬에 머물고, 읽기부터 쓰기까지가 한 번에 끝난다. 해적이 끼어들 틈이 없다. 이 extension 은 Island 선언과 같은 file 에서 모든 mode 로 통과했다.


transaction 단위의 설계

세션이 여기서 건네는 원칙은 둘이다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

  • actor 를 짤 때는 어떤 순서로 끼어들어도 괜찮은 sync 한 transactional operation 을 먼저 찾는다. 각 operation 이 끝났을 때 actor 는 언제나 일관된 상태여야 한다.
  • async 한 actor operation 은 단순하게 유지한다. sync operation 을 몇 개 묶는 정도로 두고, await 를 만나는 지점마다 actor 가 멀쩡한 상태인지 확인한다.

actor reentrancy 가 왜 생기는지와 await 뒤에 가정을 다시 확인해야 하는 이유는 Protect mutable state with Swift actors 에서 더 자세히 다뤘다.


ordering

네 번째 주제는 순서다. 동시성 program 에서 일의 순서는 기본으로 보장되지 않는데, 순서가 꼭 필요한 일도 있다.


순서가 필요한 일

사용자 입력이나 server 에서 오는 message 처럼 event 가 흘러 들어오는 경우가 그렇다. 사용자는 각 event 의 효과가 일어난 순서대로 나타나기를 기대한다.

출처: WWDC22 - Eliminate data races using Swift Concurrency


actor 와 FIFO

actor 는 순서를 지켜 주는 도구가 아니다. actor 는 들어온 순서대로가 아니라 priority 가 높은 일을 먼저 실행한다. 그렇게 해서 priority 가 낮은 일 뒤에 높은 일이 갇히는 priority inversion 을 없앤다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

이 점이 serial DispatchQueue 와의 중요한 의미 차이다. serial queue 는 엄격하게 first-in, first-out 으로 실행한다. serial queue 를 actor 로 기계적으로 바꾸면서 순서 보장까지 따라올 거라고 기대하면 안 된다.


순서를 지키는 도구

Swift Concurrency 에서 순서가 필요할 때 쓰는 도구는 둘이다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

첫째는 task 다. task 하나의 안에서는 code 가 위에서 아래로 실행되므로, 순서가 중요한 일은 한 task 안에 이어서 쓰면 된다.

둘째는 AsyncStream 이다. event 의 흐름을 stream 으로 만들면 여러 곳에서 event 를 밀어 넣어도 받는 쪽은 for await 로 하나씩 순서대로 꺼낸다.

1
2
3
4
5
func handle(eventStream: AsyncStream<Event>) async {
  for await event in eventStream {
    await process(event)
  }
}

세션의 조각은 for await loop 뿐이다. Sendable 인 Event struct, 빈 process(_:), loop 를 감싸는 handle(eventStream:) 을 채웠고 모든 mode 에서 통과했다.

AsyncStream

AsyncStream 은 closure 나 continuation 으로 element 를 공급하는 AsyncSequence 이고, 넣은 순서대로 element 를 전달한다.


strict concurrency checking 의 단계적 도입

마지막 장은 이 model 을 기존 code 에 어떻게 들여오느냐다. Sendable 검사로 isolation 을 지키는 것이 data race 를 없애는 길이지만, 이미 있는 code 전체에 한꺼번에 적용할 수는 없다. 그래서 Swift 5 기간 동안 검사를 단계적으로 켜고 Swift 6 에서 완성한다는 계획을 세션은 밝힌다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

Swift 5.7 부터 Xcode 에 Strict Concurrency Checking 이라는 build setting 이 생겼고 값은 Minimal, Targeted, Complete 셋이다. compiler flag 로는 -strict-concurrency=minimal, targeted, complete 에 해당한다.

검사에는 세션과 같은 조건을 만들려고 Chicken 을 FarmAnimals 라는 별도 module 로 따로 build 했다. module 안의 Chicken 은 public final class 이고 Sendable 표시가 없다.


Minimal

기본값이다. 개발자가 명시적으로 Sendable 이라고 적은 곳만 검사한다. Swift 5.5, 5.6 의 동작과 같다.

1
2
3
4
import FarmAnimals
struct Coop: Sendable {
  var flock: [Chicken]
}

Coop 을 Sendable 이라고 적었으니 검사 대상이 되고, Chicken 이 Sendable 이 아니라는 진단이 나온다. Swift 6 에서는 error 가 될 내용이다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

다만 Swift 5 에서는 warning 으로만 나온다. 그래야 문제를 하나씩 고쳐 나갈 수 있다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

지금 compiler 의 결과도 같다. @preconcurrency 를 권하는 warning 이 하나 더 붙는다.

1
2
3
4
Swift 5 (세 단계 모두) : warning: stored property 'flock' of 'Sendable'-conforming struct 'Coop' contains non-Sendable type 'Chicken'; this is an error in the Swift 6 language mode
                        warning: add '@preconcurrency' to suppress 'Sendable'-related warnings from module 'FarmAnimals'
Swift 6               : error: stored property 'flock' of 'Sendable'-conforming struct 'Coop' contains non-Sendable type 'Chicken'
                        warning: add '@preconcurrency' to treat 'Sendable'-related errors from module 'FarmAnimals' as warnings

Targeted

한 단계 올리면 Swift Concurrency 를 이미 쓰고 있는 code 까지 검사 범위에 들어온다. async/await, task, actor 를 쓴 곳이다.

1
2
3
4
5
6
7
8
9
10
11
import FarmAnimals

func visit(coop: Coop) async {
  guard let favorite = coop.flock.randomElement() else {
    return
  }

  Task {
    favorite.play()
  }
}

출처: WWDC22 - Eliminate data races using Swift Concurrency

새 task 가 non-Sendable 인 favorite 을 capture 하므로 세션 화면에서는 Targeted 단계에서 warning 이 나온다. 지금 compiler 는 다르게 나왔다. 검사할 때는 Coop 을 Sendable 표시 없는 struct 로 같은 file 에 두었다.

1
2
3
Swift 5, minimal / targeted : 진단 없음
Swift 5, complete           : warning: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure; this is an error in the Swift 6 language mode
Swift 6                     : error: 같은 문구

Targeted 에서 진단이 사라지고 Complete 에서만 나온다. 문구도 @Sendable closure 의 capture 가 아니라 sending parameter 로 바뀌었다. Task initializer 의 선언이 @Sendable 에서 sending 으로 바뀐 결과로 보인다. 세 단계의 경계가 2022년과 똑같지는 않다는 뜻이다.

이런 진단은 내가 고칠 수 없는 곳을 가리킬 때가 있다. Chicken 은 다른 module 의 type 이고, 그 module 이 아직 Sendable 을 정리하지 않았을 수 있다. 그럴 때 쓰는 것이 @preconcurrency 다.

1
@preconcurrency import FarmAnimals

출처: WWDC22 - Eliminate data races using Swift Concurrency

import 에 @preconcurrency 를 붙이면 그 module 에서 온 type 에 대한 Sendable 진단이 그 file 에서 꺼진다. 같은 code 에 이 attribute 만 붙여 다시 돌렸더니 visit(coop:) 과 앞의 Coop: Sendable 둘 다 Swift 5 의 세 단계와 Swift 6 mode 에서 진단이 없어졌다.

이것은 임시 조치다. 나중에 FarmAnimals 가 갱신되어 Chicken 이 Sendable 이 되면 @preconcurrency 를 지우면 되고, 반대로 Sendable 이 아니라고 확정되면 warning 이 다시 돌아와서 내 code 의 가정을 고쳐야 한다는 것을 알려 준다.

출처: WWDC22 - Eliminate data races using Swift Concurrency


Complete

마지막 단계는 Swift 6 의 의미에 가장 가깝다. Swift Concurrency 를 쓰는지와 상관없이 module 의 모든 code 를 검사한다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

1
2
3
4
5
6
7
8
9
10
11
12
13
import FarmAnimals

func doWork(_ body: @escaping () -> Void) {
  DispatchQueue.global().async {
    body()
  }
}

func visit(friend: Chicken) {
  doWork {
    friend.play()
  }
}

이 code 에는 async/await 도 task 도 없다. 그래서 앞의 두 단계에서는 조용하다. Complete 에서는 DispatchQueue 의 async 가 @Sendable closure 를 받는다는 사실이 검사에 들어온다. body 는 @Sendable 이 아니므로 warning 이 나온다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

1
2
3
Swift 5, minimal / targeted : 진단 없음
Swift 5, complete           : warning: capture of 'body' with non-Sendable type '() -> Void' in a '@Sendable' closure
Swift 6                     : 같은 warning

이 진단은 Swift 6 mode 에서도 warning 으로 나왔다. 고치는 방법은 body parameter 를 @Sendable 로 선언하는 것이다.

1
2
3
4
5
func doWork(_ body: @Sendable @escaping () -> Void) {
  DispatchQueue.global().async {
    body()
  }
}

그러면 doWork 안의 warning 은 사라지고, 이번에는 doWork 를 부르는 쪽에서 진짜 문제가 드러난다. visit(friend:) 가 non-Sendable 인 friend 를 다른 thread 에서 도는 closure 로 넘기고 있었다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

1
2
3
Swift 5, minimal / targeted : 진단 없음
Swift 5, complete           : warning: capture of 'friend' with non-Sendable type 'Chicken' in a '@Sendable' closure; this is an error in the Swift 6 language mode
Swift 6                     : error: capture of 'friend' with non-Sendable type 'Chicken' in a '@Sendable' closure

검사가 code 를 따라 올라가며 원래부터 있던 data race 를 찾아낸 것이다. Complete 는 이런 숨은 문제를 찾아 준다.

DispatchQueue

DispatchQueue 는 작업을 serial 또는 concurrent 로 실행하는 GCD 의 queue 이고, global() 은 system 이 제공하는 concurrent queue 를 돌려준다.


세션의 마무리

Doug 는 data race 안전으로 가는 길을 두 가지 조언으로 요약한다.

출처: WWDC22 - Eliminate data races using Swift Concurrency

  • strict concurrency checking 은 module 하나씩, 단계를 하나씩 올린다. 한 번에 전부 켜려고 하지 않는다.
  • 다른 module 때문에 나오는 warning 은 @preconcurrency 로 눌러 두는 것을 꺼리지 않는다. 그 module 이 준비되면 compiler 가 다시 알려 준다.

Swift 는 memory safety 로 한 종류의 bug 를 없앴고, 같은 방식으로 data race 라는 또 한 종류의 bug 를 compile 시점에 없애려 한다는 말로 세션은 끝난다.


정리

주제핵심
task isolationtask 는 sequential, asynchronous, self-contained 다. 경계를 넘는 값은 Sendable 이어야 한다
Sendablevalue type 은 안의 것이 모두 Sendable 이면 된다. class 는 final 에 immutable storage 일 때만. 직접 동기화하면 @unchecked Sendable
actor isolationactor 위에는 한 번에 한 task. 들어가고 나올 때 Sendable 검사. actor reference 는 Sendable
격리 여부Task { } 는 isolation 을 물려받고 Task.detached { } 는 물려받지 않는다. non-isolated sync code 는 부른 곳을 따른다
main actorUI 를 맡는 큰 actor. @MainActor 를 함수, closure, type 에 붙인다. 긴 작업은 금물
atomicityawait 사이에 다른 task 가 끼어든다. 한 묶음의 일은 actor 의 sync method 로
orderingactor 는 FIFO 가 아니다. 순서는 task 하나 또는 AsyncStream 으로
도입Minimal, Targeted, Complete 순서로. 남의 module 은 @preconcurrency import

실제 프로젝트에 가져갈 점은 다음과 같다.

  • 다른 task 나 actor 로 넘길 data 는 struct 와 enum 으로 설계한다. class 를 넘겨야 한다면 actor 로 감싸거나 immutable 하게 만든다.
  • @unchecked Sendable 은 lock 으로 실제 동기화를 하는 type 에만 쓴다. warning 을 없애는 용도로 쓰면 data race 를 숨기는 것과 같다.
  • actor 의 method 를 짤 때 읽기와 쓰기가 한 묶음이어야 하면 그 사이에 await 를 두지 않는다. 밖에서 읽고 고쳐서 다시 넣는 형태는 actor 안의 sync method 로 옮긴다.
  • serial queue 를 actor 로 바꿀 때 순서 보장에 기대던 곳이 있는지 확인한다. 있다면 AsyncStream 으로 순서를 따로 만든다.
  • 오래된 code base 는 module 단위로 Complete 까지 올려 본다. task 를 쓰지 않는 GCD code 의 data race 는 Complete 에서만 보인다.
  • 세션의 진단 문구와 단계별 결과는 지금 compiler 와 다를 수 있다. 위 결과처럼 2022년에 Targeted 에서 나오던 warning 이 지금은 Complete 에서만 나오기도 하고, region-based isolation 덕분에 예전에는 막히던 code 가 통과하기도 한다.

관련 글


참고자료

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.