포스트

[WWDC21] Swift concurrency: Behind the scenes

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


세션 정보


한 줄 요약

Swift concurrency 는 thread 를 block 하지 않는다는 약속 위에 서 있다. 이 약속 덕분에 runtime 은 CPU core 수만큼의 thread 만으로 일을 돌릴 수 있고, GCD 에서 흔했던 thread explosion 과 과도한 context switch 가 사라진다. 그 대신 개발자는 이 약속을 깨는 code 를 쓰지 않아야 한다.


세션의 구성

세션은 Swift concurrency 의 기능을 소개하는 자리가 아니다. async/await, structured concurrency, actor 가 왜 지금의 모습으로 설계되었는지를 runtime 과 thread 수준에서 설명하는 고급 세션이다. Rokhini 는 이 기능들이 낯설다면 다른 세션을 먼저 보라고 권한다.

출처: WWDC21 - Swift concurrency: Behind the scenes

화면에 나온 세 세션 가운데 Meet async/await in Swift 와 Protect mutable state with Swift actors 는 이 블로그에 정리해 두었다. 나머지 하나는 Explore structured concurrency in Swift 다.

세션은 크게 두 부분이다.

순서내용발표
1threading model: GCD 의 방식과 문제Rokhini
2threading model: Swift concurrency 의 방식, async 함수의 내부 동작Rokhini, Varun
3Swift concurrency 를 도입할 때의 고려 사항Rokhini
4동기화: mutual exclusion 과 actor hoppingVarun
5동기화: reentrancy 와 우선순위Varun
6동기화: main actorVarun

두 사람은 성능과 효율을 계속 강조한다. Swift concurrency 는 code 를 안전하게 만드는 것만이 목적이 아니고, 성능까지 고려해서 설계되었다는 것이 세션 전체의 주장이다.


GCD 의 threading model

Swift concurrency 의 threading model 을 이해하려면 먼저 지금까지 쓰던 Grand Central Dispatch 가 thread 를 어떻게 다루는지 알아야 한다. 세션은 news feed reader 앱을 예로 든다.


news feed reader 앱

앱에는 UI 를 맡는 main thread, 사용자가 구독한 news feed 를 기억하는 database, feed 의 최신 내용을 받아 오는 networking subsystem 이 있다. 사용자가 최신 news 를 요청하면 main thread 가 그 event 를 처리하고, 요청을 database 작업용 serial queue 로 dispatch async 한다.

출처: WWDC21 - Swift concurrency: Behind the scenes

이렇게 나누는 이유는 둘이다. 일을 다른 queue 로 보내면 양이 많아도 main thread 는 계속 사용자 입력에 반응할 수 있다. 그리고 serial queue 는 mutual exclusion 을 보장하므로 database 접근이 보호된다.

database queue 에서는 구독한 feed 를 하나씩 돌면서 feed 마다 URLSession 으로 network request 를 건다.

출처: WWDC21 - Swift concurrency: Behind the scenes

request 결과가 도착하면 URLSession 의 callback 이 delegate queue 에서 불린다. 이 앱에서는 delegate queue 가 concurrent queue 다. 각 completion handler 는 받은 내용을 cache 해 두려고 database 를 sync 로 갱신하고, 끝으로 main thread 를 깨워 UI 를 새로 그린다.

출처: WWDC21 - Swift concurrency: Behind the scenes

network request 를 처리하는 code 는 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
final class FeedUpdater: NSObject, URLSessionDelegate {
    let concurrentQueue = OperationQueue()
    let databaseQueue = DispatchQueue(label: "database")
    let feedsToUpdate: [Feed] = []

    func deserializeArticles(from data: Data) throws -> [Article] { [] }
    func updateDatabase(with articles: [Article], for feed: Feed) { }

    func update() {
        let urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: concurrentQueue)

        for feed in feedsToUpdate {
            let dataTask = urlSession.dataTask(with: feed.url) { data, response, error in
                // ...
                guard let data = data else { return }
                do {
                    let articles = try self.deserializeArticles(from: data)
                    self.databaseQueue.sync {
                        self.updateDatabase(with: articles, for: feed)
                    }
                } catch { /* ... */ }
            }
            dataTask.resume()
        }
    }
}

URLSession 의 init(configuration:delegate:delegateQueue:)

init(configuration:delegate:delegateQueue:) 은 delegate 와 completion handler 를 부를 queue 를 정해서 session 을 만드는 initializer 다.

dataTask(with:completionHandler:)

dataTask(with:completionHandler:) 은 URL 의 내용을 받아 온 뒤 completion handler 를 부르는 task 를 만드는 method 다.

DispatchQueue 의 sync

sync(execute:) 은 queue 에 일을 넣고 그 일이 끝날 때까지 호출한 thread 를 기다리게 하는 method 다.

세션 page 의 snippet 은 함수 둘과 top-level 문장으로 되어 있다. compile 하려고 Article 과 Feed, queue 선언을 채우고 전체를 class 하나로 감쌌으며, closure 안의 호출에 self. 를 붙였다. delegateQueue 의 type 이 OperationQueue 라서 concurrentQueue 는 OperationQueue 로 선언했다. 이 형태는 Swift 5 와 Swift 6 language mode 에서 모두 통과했다.

평범하고 그럴듯한 code 지만 Rokhini 는 여기에 숨은 성능 함정이 있다고 말한다.

출처: WWDC21 - Swift concurrency: Behind the scenes


GCD 의 thread 생성 방식

GCD 는 queue 에 일이 들어오면 그 일을 처리할 thread 를 띄운다. concurrent queue 는 여러 일을 한꺼번에 처리할 수 있으므로 CPU core 가 모두 찰 때까지 thread 를 여러 개 띄운다.

문제는 thread 가 block 될 때다. 어떤 thread 가 block 되었는데 concurrent queue 에 할 일이 더 남아 있으면 GCD 는 남은 일을 처리할 thread 를 더 띄운다.

출처: WWDC21 - Swift concurrency: Behind the scenes

이렇게 하는 이유는 둘이다.

  • process 에 thread 를 하나 더 주면 core 마다 일하는 thread 가 항상 하나씩 있게 된다. 앱의 concurrency 수준이 유지된다.
  • block 된 thread 는 semaphore 같은 resource 를 기다리는 중일 수 있다. 새로 띄운 thread 가 그 resource 를 풀어 줄 수도 있다.

출처: WWDC21 - Swift concurrency: Behind the scenes


news 앱의 CPU 실행

이 동작을 news 앱에 대입해 본다. core 가 둘인 Apple Watch 라면 GCD 는 먼저 feed 결과를 처리할 thread 둘을 띄운다. 두 thread 가 database queue 에 접근하다 block 되면 networking queue 의 남은 일을 처리하려고 thread 를 더 만든다. CPU 는 thread 사이를 오가야 하고, 그림의 흰 세로줄이 그 context switch 다.

출처: WWDC21 - Swift concurrency: Behind the scenes

feed 가 100개쯤 되면 URL data task 100개가 각자 completion block 을 concurrent queue 에 올린다. 그 callback 이 database queue 에서 block 될 때마다 GCD 는 thread 를 더 띄우고, 결국 앱은 thread 를 아주 많이 갖게 된다.


thread explosion 이란?

thread explosion 은 CPU core 수보다 훨씬 많은 thread 가 만들어져 system 이 overcommit 되는 상태다. 세션의 예로는 core 가 여섯인 iPhone 에서 feed 100개를 처리하면 core 수의 16배에 이르는 thread 가 생긴다.

출처: WWDC21 - Swift concurrency: Behind the scenes

thread 가 많다고 무엇이 나쁜지는 세 가지로 정리된다.

첫째는 deadlock 가능성이다. 이 부분은 세션에서 자세히 다루지 않고 화면에 이전 세션 둘을 적어 둔다. 그중 하나가 Modernizing Grand Central Dispatch Usage 다.

둘째는 memory overhead 다. block 된 thread 는 다시 실행되기를 기다리면서 귀한 memory 와 resource 를 계속 쥐고 있다. thread 마다 stack 이 있고, thread 를 추적하는 kernel data structure 가 딸려 있다. 어떤 thread 는 lock 을 쥔 채 block 되어 있어서 실행 중인 다른 thread 가 그 lock 을 기다릴 수도 있다. 일을 진행하지도 않는 thread 가 들고 있기에는 큰 비용이다.

출처: WWDC21 - Swift concurrency: Behind the scenes

셋째는 scheduling overhead 다. thread 가 새로 뜨면 CPU 는 이전 thread 에서 새 thread 로 넘어가려고 full thread context switch 를 해야 한다. block 되었던 thread 가 다시 실행 가능해지면 scheduler 는 thread 들이 모두 조금씩 진행하도록 CPU 시간을 나누어 준다. 이런 일이 몇 번 일어나는 정도는 괜찮다. 하지만 thread explosion 상태에서는 core 가 몇 개뿐인 기기에서 수백 개의 thread 를 나누어 돌려야 하므로 context switch 가 지나치게 많아진다. thread 를 바꾸는 데 드는 지연이 실제로 하는 일의 양을 넘어서면 CPU 는 비효율적으로 돌게 된다.

출처: WWDC21 - Swift concurrency: Behind the scenes

GCD queue 로 code 를 짤 때는 이런 threading 동작의 미묘한 부분을 놓치기 쉽고, 그 결과가 성능 저하와 예상보다 큰 overhead 로 돌아온다.


Swift concurrency 의 threading model

Swift concurrency 는 위 문제를 염두에 두고 설계되었다. 통제되고 구조화되어 있으며 안전한 concurrency 를 언어 차원에서 주는 것이 목표다.


목표로 하는 실행 모습

같은 news 앱을 Swift concurrency 로 바꾸면 이런 실행을 기대한다. core 가 둘인 system 에서 thread 는 둘뿐이고, thread context switch 는 없다.

출처: WWDC21 - Swift concurrency: Behind the scenes

block 된 thread 는 모두 사라지고 그 자리를 continuation 이 대신한다. thread 는 context switch 를 하는 대신 같은 thread 위에서 continuation 사이를 옮겨 다닌다. 이 전환의 비용은 function call 한 번 수준이다.

출처: WWDC21 - Swift concurrency: Behind the scenes


continuation 이란?

continuation 은 중단된 일을 나중에 이어서 할 수 있게 그 지점을 기록해 두는 가벼운 object 다. GCD 에서는 일이 멈추면 thread 가 통째로 멈춘 채 남았지만, Swift concurrency 에서는 continuation 만 남고 thread 는 다른 일을 하러 간다.


runtime contract 와 두 가지 언어 기능

정리하면 Swift concurrency 가 원하는 runtime 동작은 이렇다. CPU core 수만큼만 thread 를 만들고, 일이 block 되면 thread 가 싸고 효율적으로 다른 일로 넘어간다. 개발자는 읽기 쉬운 직선형 code 를 쓰면서 안전하고 통제된 concurrency 를 얻는다.

출처: WWDC21 - Swift concurrency: Behind the scenes

이 동작을 얻으려면 OS 에 약속이 하나 필요하다. thread 가 block 되지 않는다는 runtime contract 다. 이 약속은 언어가 뒷받침해 줄 때만 지킬 수 있다. Swift 의 concurrency model 은 처음부터 이 약속을 지키도록 설계되었고, 세션은 그 근거가 되는 언어 기능 둘을 든다.

출처: WWDC21 - Swift concurrency: Behind the scenes

하나는 await 의 semantics 이고, 다른 하나는 Swift runtime 이 task 사이의 dependency 를 추적한다는 점이다.


task group 으로 다시 쓴 code

두 기능을 보려고 앞의 GCD code 를 Swift concurrency 로 바꾼다. database 를 갱신하는 helper 를 async 함수로 만들고, completion handler 대신 task group 을 써서 feed 마다 child task 를 만든다. child task 는 URL 에서 내용을 받고, deserialize 하고, async 함수로 database 를 갱신한 뒤 결과를 돌려준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func deserializeArticles(from data: Data) throws -> [Article] { [] }
func updateDatabase(with articles: [Article], for feed: Feed) async { }

func update(_ feedsToUpdate: [Feed]) async {
    await withThrowingTaskGroup(of: [Article].self) { group in
        for feed in feedsToUpdate {
            group.addTask {
                let (data, _) = try await URLSession.shared.data(from: feed.url)
                // ...
                let articles = try deserializeArticles(from: data)
                await updateDatabase(with: articles, for: feed)
                return articles
            }
        }
    }
}

withThrowingTaskGroup

withThrowingTaskGroup(of:returning:isolation:body:) 은 error 를 던질 수 있는 child task 들을 담는 group 을 만들고, child task 가 모두 끝날 때까지 scope 를 벗어나지 않는 함수다.

addTask

addTask(priority:operation:) 은 group 에 child task 를 하나 추가하는 method 다.

URLSession 의 data(from:)

data(from:delegate:) 은 URL 의 내용을 받아 (Data, URLResponse) 로 돌려주는 async method 다.

세션의 code 와 다른 곳이 둘 있다. 화면과 세션 page 에서는 child task 를 group.async 로 만든다. 지금 compiler 는 이 이름에 “renamed to addTask” 라는 deprecated warning 을 내므로 addTask 로 바꾸었다. 그리고 쓰지 않는 response 는 warning 이 나서 _ 로 받았다. Article 과 Feed 는 Sendable struct 로 채웠고, top-level 문장은 함수로 감쌌다. 이 형태는 Swift 5 와 Swift 6 language mode 에서 warning 없이 통과했다.

출처: WWDC21 - Swift concurrency: Behind the scenes

GCD 버전과 비교하면 차이가 분명하다. URLSession 의 결과를 기다리는 곳과 database 갱신을 기다리는 곳이 모두 await 다. await 는 thread 를 block 하지 않고 함수를 suspend 하며, 그 사이 thread 는 다른 task 를 실행한다.


sync 함수의 stack

await 가 어떻게 thread 를 놓아 줄 수 있는지는 Varun 이 설명한다. 먼저 async 가 아닌 함수부터 본다.

실행 중인 program 의 thread 는 저마다 stack 을 하나씩 갖고, function call 의 상태를 거기에 저장한다.

출처: WWDC21 - Swift concurrency: Behind the scenes

thread 가 함수를 호출하면 stack 에 새 frame 이 쌓인다. 함수는 이 frame 에 local 변수와 return address 같은 정보를 둔다. 함수가 return 하면 frame 은 stack 에서 빠진다.

출처: WWDC21 - Swift concurrency: Behind the scenes


async 함수의 async frame

이제 async 함수다. 예제는 updateDatabase 가 Feed 의 add(_:) 를 부르고, add(_:) 가 Database 의 save(_:for:) 를 부르는 구조다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
typealias ID = UUID
struct Article: Sendable { var title: String }

actor Database {
    func save(_ newArticles: [Article], for feed: Feed) async throws -> [ID] {
        newArticles.map { _ in ID() }
    }
}

let database = Database()

actor Feed {
    var articles: [ID: Article] = [:]

    func add(_ newArticles: [Article]) async throws {
        let ids = try await database.save(newArticles, for: self)
        for (id, article) in zip(ids, newArticles) {
            articles[id] = article
        }
    }
}

func updateDatabase(with articles: [Article], for feed: Feed) async throws {
    // skip old articles ...
    try await feed.add(articles)
}

zip

zip(::) 은 두 sequence 의 원소를 순서대로 짝지은 sequence 를 만드는 함수다.

세션 page 의 snippet 은 “on Database”, “on Feed” 라는 주석과 함께 method 만 보여 준다. 세션 뒷부분에서 database 와 feed 를 actor 로 바꾸므로 둘을 actor 로 선언했고, ID 와 Article, global database, save 의 body 는 내가 채웠다. 이 형태는 Swift 5 와 Swift 6 language mode 에서 모두 통과했다.

thread 가 updateDatabase 에서 add(_:) 를 호출한 시점을 보자. 가장 최근의 stack frame 은 add 의 것이다. 이 stack frame 에는 suspension point 를 넘어서까지 살아 있을 필요가 없는 local 변수가 들어간다.

출처: WWDC21 - Swift concurrency: Behind the scenes

add 의 body 에는 await 로 표시된 suspension point 가 하나 있다. for loop 의 id 와 article 은 그 뒤에 정의되고 사이에 suspension 없이 바로 쓰이므로 stack frame 에 저장된다.

heap 에는 updateDatabase 용과 add 용 async frame 이 하나씩 있다. async frame 은 suspension point 를 넘어서도 필요한 정보를 담는다. newArticles 는 await 보다 먼저 정의되었고 await 뒤에도 써야 하므로 add 의 async frame 이 이 값을 챙겨 둔다.

출처: WWDC21 - Swift concurrency: Behind the scenes

thread 가 실행을 계속해서 save 가 시작되면 add 의 stack frame 은 save 의 stack frame 으로 교체된다. 새 frame 을 위에 쌓는 것이 아니다. 나중에 필요한 변수는 이미 async frame 의 list 에 들어 있으므로 맨 위 frame 을 바꿔 끼워도 된다. save 도 자기 async frame 을 하나 얻는다.

출처: WWDC21 - Swift concurrency: Behind the scenes

article 을 database 에 저장하는 동안 thread 가 block 되어 기다리는 것보다 다른 쓸모 있는 일을 하는 편이 낫다. save 가 suspend 되면 thread 는 block 되지 않고 다른 일에 재사용된다. suspension point 를 넘어 유지되어야 하는 정보는 모두 heap 에 있어서 나중에 실행을 이어 갈 수 있다. 이 async frame 의 list 가 바로 continuation 의 runtime 표현이다.

출처: WWDC21 - Swift concurrency: Behind the scenes

시간이 지나 database request 가 끝나고 어떤 thread 가 한가해졌다고 하자. 이 thread 는 처음의 thread 일 수도 있고 다른 thread 일 수도 있다. 이 thread 에서 save 가 재개된다.

출처: WWDC21 - Swift concurrency: Behind the scenes

save 가 ID 들을 돌려주고 끝나면 save 의 stack frame 은 다시 add 의 stack frame 으로 교체된다. 이어서 thread 는 zip 을 실행한다. 두 array 를 짝짓는 일은 async 가 아니므로 평소처럼 새 stack frame 이 쌓였다가 빠진다.

출처: WWDC21 - Swift concurrency: Behind the scenes

Swift 가 OS 의 stack 을 그대로 쓰기 때문에 async 든 아니든 Swift code 는 C 와 Objective-C 를 효율적으로 호출할 수 있다. C 와 Objective-C 쪽에서도 async 가 아닌 Swift code 를 지금처럼 효율적으로 호출할 수 있다.


task dependency 추적

두 번째 언어 기능은 다시 Rokhini 가 설명한다. 함수는 await, 곧 potential suspension point 에서 continuation 으로 나뉜다. 예제에서는 URLSession 의 data task 가 async 함수이고, 그 뒤에 남은 일이 continuation 이다. continuation 은 그 async 함수가 끝난 뒤에만 실행될 수 있고, 이 dependency 는 Swift concurrency runtime 이 추적한다.

출처: WWDC21 - Swift concurrency: Behind the scenes

task group 도 마찬가지다. parent task 는 child task 를 여럿 만들 수 있고, child task 가 모두 끝나야 parent 가 진행할 수 있다. 이 dependency 는 task group 의 scope 라는 형태로 code 에 드러나 있어서 compiler 와 runtime 이 분명히 안다.

출처: WWDC21 - Swift concurrency: Behind the scenes

Swift 에서 task 가 await 할 수 있는 것은 runtime 이 아는 다른 task 뿐이다. continuation 이든 child task 든 그렇다. 그래서 Swift concurrency 의 primitive 로 짠 code 는 task 사이의 dependency chain 을 runtime 에게 분명히 알려 준다.

thread 는 이 dependency 를 따져서 일을 고를 수 있고, 항상 다른 task 를 집어 들어 진행할 수 있다. 이것이 thread 가 언제나 forward progress 를 한다는 runtime contract 다.

출처: WWDC21 - Swift concurrency: Behind the scenes


cooperative thread pool 이란?

cooperative thread pool 은 Swift concurrency 의 default executor 로, CPU core 수만큼의 thread 만 만드는 thread pool 이다. runtime contract 덕분에 OS 가 Swift concurrency 를 더 깊이 지원할 수 있었고, 그 결과물이 이 pool 이다.

출처: WWDC21 - Swift concurrency: Behind the scenes

thread 수가 core 수를 넘지 않으므로 system 이 overcommit 되지 않는다. GCD 의 concurrent queue 는 일이 block 되면 thread 를 더 띄우지만, Swift 에서는 thread 가 항상 진행할 수 있으므로 default runtime 이 thread 수를 신중하게 통제할 수 있다. 필요한 만큼의 concurrency 는 주되 지나친 concurrency 의 함정은 피한다.

이전 GCD 세션들은 앱을 subsystem 으로 나누고 subsystem 마다 serial queue 를 하나씩 두어 concurrency 를 통제하라고 권했다. 이 방식에서는 thread explosion 위험 때문에 subsystem 하나 안에서 concurrency 를 1보다 크게 잡기가 어려웠다. Swift 에서는 언어가 강한 invariant 를 주고 runtime 이 그것을 활용하므로, default runtime 만으로 더 잘 통제된 concurrency 를 얻는다.

출처: WWDC21 - Swift concurrency: Behind the scenes

화면 아래에 적힌 이전 세션은 Modernizing Grand Central Dispatch Usage 와 Concurrent Programming With GCD in Swift 3 이다.


도입할 때의 고려 사항

threading model 을 알았으니 code 를 Swift concurrency 로 옮길 때 염두에 둘 점을 본다. Rokhini 는 세 가지를 든다.


성능 비용

sync code 를 async code 로 바꾼다고 저절로 빨라지지 않는다. concurrency 에는 비용이 따른다. Swift runtime 안에서 memory allocation 과 logic 이 추가로 돈다. 그러므로 concurrency 를 도입해 얻는 이득이 그것을 관리하는 비용보다 클 때만 새로 code 를 쓰는 것이 좋다.

화면의 예는 UserDefaults 에서 값 하나를 읽으려고 child task 를 만드는 code 다.

1
2
3
4
5
6
7
8
9
10
11
func layout(userDefaults: UserDefaults) async {
    async let isThumbnailView =
        userDefaults.bool(forKey: "ViewType")

    // Fetch latest articles
    if await isThumbnailView {
        // Perform thumbnail view layout
    } else {
        // Perform list view layout
    }
}

UserDefaults 의 bool(forKey:)

UserDefaults 는 앱의 설정값을 key 로 저장하고 읽는 type 이고, bool(forKey:) 는 key 에 해당하는 값을 Bool 로 읽는 method 다.

이 snippet 은 세션 page 에는 없고 화면에만 나온다. userDefaults 를 parameter 로 받는 함수로 감싼 것은 내가 한 일이다. Swift 5 language mode 에서는 통과했지만 Swift 6 language mode 에서는 “sending ‘userDefaults’ risks causing data races” error 가 났다. 세션의 지적은 성능에 관한 것이지만, 지금 compiler 는 이 code 를 data race 관점에서도 막는다.

출처: WWDC21 - Swift concurrency: Behind the scenes

child task 가 하는 유용한 일이 task 를 만들고 관리하는 비용보다 작으므로 여기서는 얻는 것이 없다. 세션은 Swift concurrency 를 도입하면서 Instruments 의 system trace 로 code 의 성능 특성을 측정해 보라고 권한다.


await 와 atomicity

두 번째는 await 주변의 atomicity 다. Swift 는 await 앞의 code 를 실행한 thread 가 continuation 도 실행한다고 보장하지 않는다. await 는 task 가 스스로 실행을 내려놓을 수 있는 지점이고, code 에서 atomicity 가 깨진다는 것을 드러내는 표시다.

출처: WWDC21 - Swift concurrency: Behind the scenes

여기서 두 가지 주의가 나온다.

출처: WWDC21 - Swift concurrency: Behind the scenes

  • lock 을 쥔 채로 await 를 넘지 않는다.
  • thread-specific data 는 await 를 넘어서 유지되지 않는다. thread locality 를 가정한 code 는 await 의 suspension 동작을 고려해서 다시 살펴야 한다.

runtime contract 유지

세 번째는 runtime contract 다. cooperative thread pool 이 제대로 돌려면 thread 가 항상 forward progress 를 할 수 있어야 하고, Swift concurrency 로 옮긴 뒤에도 code 가 이 약속을 계속 지키는지 살펴야 한다. 세션은 동기화 수단을 셋으로 나눈다.

출처: WWDC21 - Swift concurrency: Behind the scenes

분류primitivecompiler 지원
안전await, actor, task groupcompiler 가 강제
주의 필요sync code 안의 os_unfair_lock, NSLock없음
unsafeDispatchSemaphore, pthread_cond, NSCondition, pthread_rw_lock 등없음

안전한 쪽은 dependency 가 compile time 에 알려지는 primitive 다. compiler 가 규칙을 강제하므로 runtime contract 가 유지된다.

os_unfair_lock 이나 NSLock 도 쓸 수 있지만 주의가 필요하다. sync code 에서 짧고 잘 알려진 critical section 의 data 를 보호하는 용도라면 안전하다. lock 을 쥔 thread 는 lock 을 풀 때까지 계속 진행할 수 있기 때문이다. contention 이 있으면 thread 가 잠깐 block 될 수 있지만 forward progress 약속을 어기는 것은 아니다. 다만 Swift concurrency 의 primitive 와 달리 compiler 가 올바른 사용을 도와주지 않으므로 제대로 쓰는 것은 개발자의 책임이다.

semaphore 와 condition variable 은 Swift concurrency 와 함께 쓰기에 unsafe 하다. 이런 primitive 는 dependency 정보를 Swift runtime 에게 숨기면서 code 의 실행에는 dependency 를 만든다. runtime 은 그 dependency 를 모르기 때문에 올바른 scheduling 결정을 내릴 수 없다.

특히 피해야 할 pattern 은 unstructured task 를 만든 다음 semaphore 같은 unsafe primitive 로 task 경계를 넘는 dependency 를 뒤늦게 거는 것이다.

1
2
3
4
5
6
7
8
9
10
11
func updateDatabase(_ asyncUpdateDatabase: @Sendable @escaping () async -> Void) {

    let semaphore = DispatchSemaphore(value: 0)

    Task {
        await asyncUpdateDatabase()
        semaphore.signal()
    }

    semaphore.wait()
}

DispatchSemaphore

DispatchSemaphore 는 counter 로 resource 접근을 조절하는 object 다. wait() 는 counter 가 0 이면 thread 를 block 하고, signal() 은 기다리는 thread 를 깨운다.

이 snippet 도 화면에만 나온다. 화면 그대로 옮겼고 Swift 5 와 Swift 6 language mode 에서 warning 없이 통과했다. 표의 “compiler 지원 없음” 그대로 compiler 는 이 pattern 을 잡아 주지 않는다.

출처: WWDC21 - Swift concurrency: Behind the scenes

이 code 에서 wait() 를 부른 thread 는 다른 thread 가 풀어 줄 때까지 semaphore 에 묶여 무기한 block 될 수 있다. thread 의 forward progress 라는 runtime contract 를 어기는 것이다.


debug 환경 변수

이런 unsafe primitive 를 code 에서 찾아내려면 앱을 다음 환경 변수와 함께 실행해 보라고 세션은 권한다.

1
LIBDISPATCH_COOPERATIVE_POOL_STRICT=1

이 값을 주면 forward progress invariant 를 강제하는 debug 용 runtime 아래에서 앱이 돈다. Xcode 에서는 project scheme 의 Run Arguments pane 에 환경 변수로 넣는다.

출처: WWDC21 - Swift concurrency: Behind the scenes

이 환경에서 앱을 돌렸을 때 cooperative thread pool 의 thread 가 hang 된 것으로 보이면 unsafe 한 blocking primitive 를 쓰고 있다는 뜻이다. 화면의 예에서는 cooperative queue 의 thread 가 semaphore 를 기다리는 함수에서 멈춰 있다.

출처: WWDC21 - Swift concurrency: Behind the scenes


actor 를 통한 동기화

여기부터는 Varun 이 actor 로 동기화가 어떻게 이루어지는지 설명한다. actor 는 한 번에 method call 하나만 실행한다는 mutual exclusion 을 보장해서 mutable state 를 concurrent 접근으로부터 보호한다. 이 보장이 actor 의 state 가 동시에 접근되지 않게 하고 data race 를 막는다.


세 가지 mutual exclusion 비교

actor 가 thread 관점에서 무엇이 다른지는 다른 mutual exclusion 수단과 비교하면 드러난다.

출처: WWDC21 - Swift concurrency: Behind the scenes

상황lock, serial queue 의 syncserial queue 의 asyncactor (cooperative pool)
contention 없음thread 재사용새 thread 요청thread 재사용
contention 있음blockingnon-blockingnon-blocking

serial queue 에 sync 로 일을 넣는 경우부터 보자. queue 가 실행 중이 아니면 contention 이 없는 것이고, 호출한 thread 가 그대로 그 일을 실행한다. context switch 가 없다. queue 가 이미 실행 중이면 contention 이 있는 것이고 호출한 thread 는 block 된다. 앞에서 본 thread explosion 을 일으키는 것이 바로 이 blocking 이다. lock 도 같은 동작을 한다.

blocking 의 문제 때문에 그동안은 dispatch async 를 권해 왔다. dispatch async 는 block 하지 않으므로 contention 이 있어도 thread explosion 으로 이어지지 않는다. 단점은 contention 이 없을 때도 Dispatch 가 새 thread 를 요청해야 한다는 것이다. 호출한 thread 는 자기 일을 계속하고 넘긴 일은 다른 thread 가 맡는다. 그래서 dispatch async 를 자주 쓰면 thread 를 깨우는 일과 context switch 가 지나치게 많아진다.

actor 는 cooperative thread pool 을 이용해 두 방식의 장점을 합친다. 실행 중이 아닌 actor 의 method 를 부르면 호출한 thread 가 그 method 를 바로 실행한다. actor 가 이미 실행 중이면 호출한 thread 는 실행하던 함수를 suspend 하고 다른 일을 집어 든다.


actor 로 바꾼 news 앱

이 성질이 news 앱에서 어떻게 작동하는지 database 와 networking subsystem 을 본다. GCD 버전에서는 database 가 serial queue, networking 이 concurrent queue 였다.

출처: WWDC21 - Swift concurrency: Behind the scenes

Swift concurrency 로 옮기면 database 의 serial queue 는 database actor 가 된다. networking 의 concurrent queue 는 news feed 마다 하나씩 둔 actor 로 바뀐다. 세션은 sports feed, weather feed, health feed 의 actor 셋만 그리지만 실제로는 훨씬 많다. 이 actor 들은 모두 cooperative thread pool 위에서 실행된다.

출처: WWDC21 - Swift concurrency: Behind the scenes

feed actor 는 article 을 저장하거나 그 밖의 일을 하려고 database 와 상호작용한다.


actor hopping 이란?

actor hopping 은 실행이 한 actor 에서 다른 actor 로 넘어가는 것이다. feed actor 가 database actor 의 method 를 부를 때 일어난다.

sports feed actor 가 cooperative pool 의 thread 위에서 실행되다가 article 을 database 에 저장하기로 했다고 하자. database 는 지금 쓰이고 있지 않다. contention 이 없는 경우다. thread 는 sports feed actor 에서 database actor 로 바로 hop 한다.

출처: WWDC21 - Swift concurrency: Behind the scenes

두 가지를 볼 수 있다. hop 하는 동안 thread 가 block 되지 않았다. 그리고 hop 에 다른 thread 가 필요하지 않았다. runtime 은 sports feed actor 의 work item 을 suspend 하고 database actor 의 work item 을 새로 만들면 된다. 그림 아래의 “Suspended actors” 줄에 sports feed 의 S1 이 들어가 있다.

database actor 가 한동안 실행되고 첫 work item D1 이 아직 끝나지 않았을 때 weather feed actor 가 다른 thread 에서 article 을 database 에 저장하려 한다고 하자.

출처: WWDC21 - Swift concurrency: Behind the scenes

database actor 에 새 work item D2 가 만들어진다. actor 는 mutual exclusion 을 보장하므로 실행 중인 work item 은 많아야 하나다. D1 이 실행 중이니 D2 는 pending 상태로 남는다.

출처: WWDC21 - Swift concurrency: Behind the scenes

actor 는 non-blocking 이기도 하다. weather feed actor 는 suspend 되고, 그 thread 는 풀려나 다른 일을 한다. 그림에서는 health feed actor 의 일을 시작한다.

출처: WWDC21 - Swift concurrency: Behind the scenes

조금 뒤 처음의 database request 가 끝나면 database actor 의 active work item 이 사라진다. 이때 runtime 은 database actor 의 pending work item 을 실행할 수도 있고, feed actor 가운데 하나를 재개할 수도 있고, 풀려난 thread 로 다른 일을 할 수도 있다.

출처: WWDC21 - Swift concurrency: Behind the scenes


serial queue 의 priority inversion

async 일이 많고 contention 도 많을 때 system 은 무엇이 더 중요한지 따져서 일을 골라야 한다. 사용자 입력처럼 priority 가 높은 일이 backup 저장 같은 background 일보다 먼저 처리되는 것이 이상적이다. actor 는 reentrancy 라는 성질 덕분에 system 이 일의 우선순위를 잘 매길 수 있게 설계되어 있다. 왜 reentrancy 가 중요한지 보려고 먼저 GCD 를 본다.

serial queue 인 database queue 가 있고, 이 queue 에 priority 가 높은 일과 낮은 일이 들어온다고 하자. 높은 쪽은 UI 를 갱신하려고 최신 data 를 가져오는 일이고, 낮은 쪽은 database 를 iCloud 로 backup 하는 일이다. 일은 만들어진 순서대로 queue 에 쌓인다.

출처: WWDC21 - Swift concurrency: Behind the scenes

dispatch queue 는 받은 일을 엄격한 first-in, first-out 순서로 실행한다. 그래서 item A 가 실행된 뒤에는 priority 가 낮은 item 다섯 개가 끝나야 다음 high-priority item 에 차례가 온다. 이것을 priority inversion 이라고 부른다.

serial queue 는 priority 가 높은 일보다 앞에 놓인 일 전부의 priority 를 끌어올리는 방법으로 이 문제를 다룬다. 앞의 일들이 더 빨리 끝나기는 한다. 하지만 1번부터 5번까지가 끝나야 B 가 시작한다는 근본 문제는 그대로다.

출처: WWDC21 - Swift concurrency: Behind the scenes

이 문제를 풀려면 semantic model 이 엄격한 first-in, first-out 에서 벗어나야 한다. 여기서 actor reentrancy 가 등장한다.


actor reentrancy 와 순서

reentrancy 가 순서와 어떻게 이어지는지 예를 본다. database actor 가 한 thread 에서 실행되다가 어떤 일을 await 하며 suspend 되고, 같은 thread 에서 sports feed actor 가 실행을 시작한다.

출처: WWDC21 - Swift concurrency: Behind the scenes

조금 뒤 sports feed actor 가 article 을 저장하려고 database actor 를 부른다. database actor 에는 pending work item D1 이 하나 있지만 지금 실행 중인 것은 없다. contention 이 없으므로 thread 는 database actor 로 hop 하고, save 작업을 위한 새 work item D2 가 만들어져 실행을 시작한다.

출처: WWDC21 - Swift concurrency: Behind the scenes

actor reentrancy 란 이전 work item 이 하나 이상 suspend 되어 있는 동안에도 actor 의 새 work item 이 진행할 수 있다는 뜻이다. mutual exclusion 은 그대로 유지된다. 어느 시점에든 실행 중인 work item 은 많아야 하나다.

얼마 뒤 D2 가 끝난다. D2 는 D1 보다 나중에 만들어졌는데 D1 보다 먼저 끝났다.

출처: WWDC21 - Swift concurrency: Behind the scenes

reentrancy 를 지원한다는 것은 actor 가 엄격한 first-in, first-out 이 아닌 순서로 item 을 실행할 수 있다는 뜻이다.

앞의 serial queue 예를 database actor 로 다시 보자. 화면의 code 도 databaseQueue.async 에서 await database.fetchLatestForDisplay() 와 await database.backUpToiCloud() 로 바뀌어 있다.

출처: WWDC21 - Swift concurrency: Behind the scenes

priority 가 높은 item A 가 먼저 실행된다. A 가 끝나면 같은 priority inversion 상황이 된다. actor 는 reentrancy 를 전제로 설계되었으므로 runtime 은 priority 가 높은 item 을 낮은 item 들 앞으로, queue 의 맨 앞으로 옮길 수 있다. 중요한 일이 먼저 실행되고 덜 중요한 일은 그 뒤를 따른다.

출처: WWDC21 - Swift concurrency: Behind the scenes

priority inversion 을 직접 해결하는 방식이고, 그만큼 scheduling 과 resource 활용이 효율적이다.


main actor 와 context switch

마지막은 main actor 다. main actor 는 system 에 원래 있던 개념인 main thread 를 추상화한 것이라 다른 actor 와 성격이 조금 다르다.

actor 로 바꾼 news 앱에서 UI 를 갱신하려면 MainActor 를 오가는 호출이 필요하다. main thread 는 cooperative pool 의 thread 와 별개이므로 이때는 context switch 가 일어난다.

출처: WWDC21 - Swift concurrency: Behind the scenes

성능에 미치는 영향을 code 로 본다. MainActor 의 updateArticles 가 loop 를 돌면서 database 에서 article 을 하나씩 읽고 article 마다 UI 를 갱신한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
typealias ID = UUID
struct Article: Sendable { var title: String }

actor Database {
    func loadArticle(with id: ID) async throws -> Article { Article(title: "") }
}

let database = Database()

@MainActor func updateUI(for article: Article) async { }

@MainActor func updateArticles(for ids: [ID]) async throws {
    for id in ids {
        let article = try await database.loadArticle(with: id)
        await updateUI(for: article)
    }
}

MainActor

MainActor 는 main thread 에서 실행되는 global actor 다. 함수에 @MainActor 를 붙이면 그 함수는 main thread 에서 실행된다.

ID 와 Article, Database actor 와 body 는 내가 채웠다. Swift 5 와 Swift 6 language mode 에서 모두 통과했다.

loop 의 iteration 마다 context switch 가 적어도 두 번 필요하다. main actor 에서 database actor 로 한 번, 그리고 돌아오는 데 한 번이다.

출처: WWDC21 - Swift concurrency: Behind the scenes

CPU 사용 모습은 이렇다. iteration 마다 context switch 가 둘씩 있으므로 두 thread 가 짧게 번갈아 실행되는 pattern 이 반복된다.

출처: WWDC21 - Swift concurrency: Behind the scenes

iteration 수가 적고 iteration 마다 하는 일이 충분히 많다면 괜찮다. 하지만 실행이 main actor 를 자주 드나들면 thread 를 바꾸는 overhead 가 쌓인다.

출처: WWDC21 - Swift concurrency: Behind the scenes

앱이 context switch 에 시간을 많이 쓰고 있다면 main actor 의 일을 batch 로 묶도록 code 를 고쳐야 한다. loop 를 loadArticles 와 updateUI 안으로 밀어 넣고, 두 함수가 값 하나가 아니라 array 를 처리하게 만든다.

1
2
3
4
5
6
7
8
9
10
11
12
actor Database {
    func loadArticles(with ids: [ID]) async throws -> [Article] { [] }
}

let database = Database()

@MainActor func updateUI(for articles: [Article]) async { }

@MainActor func updateArticles(for ids: [ID]) async throws {
    let articles = try await database.loadArticles(with: ids)
    await updateUI(for: articles)
}

세션 page 의 snippet 은 loadArticles 와 updateUI 를 body 없이 선언만 보여 준다. body 는 내가 채웠고, ID 와 Article 은 앞의 code 와 같다. 이 형태도 두 language mode 에서 통과했다.

출처: WWDC21 - Swift concurrency: Behind the scenes

batch 로 묶으면 context switch 수가 줄어든다. cooperative thread pool 안에서 actor 사이를 hop 하는 것은 빠르지만, main actor 를 오가는 hop 은 앱을 짤 때 따로 신경 써야 한다.


세션의 마무리

Varun 은 세션에서 다룬 내용을 이렇게 정리한다. Swift concurrency 를 만든 사람들은 cooperative thread pool 의 설계, block 하지 않는 suspension mechanism, actor 의 구현까지 모든 단계에서 system 을 효율적으로 만들려고 했다. 그리고 각 단계에서 runtime contract 의 어떤 측면을 활용해 앱의 성능을 끌어올렸다.

세션이 남기는 당부는 두 가지로 읽힌다. Swift concurrency 가 왜 빠른지를 이해하면 code 를 어떻게 써야 하는지도 보인다는 것, 그리고 그 성능은 개발자가 runtime contract 를 지킬 때만 유지된다는 것이다.


정리

세션의 내용을 표로 모으면 다음과 같다.

개념하는 일기억할 점
thread explosionblock 된 thread 를 대신해 thread 가 계속 늘어남memory, scheduling 비용과 deadlock 위험
continuation중단된 일의 재개 지점을 기록runtime 에서는 heap 의 async frame list
async framesuspension point 를 넘어 필요한 값을 heap 에 저장stack frame 은 교체되고 thread 는 풀려남
runtime contractthread 가 항상 forward progress 를 함await 와 dependency 추적이 뒷받침
cooperative thread poolCPU core 수만큼의 thread 로 실행block 되어도 thread 를 더 만들지 않음
actor hopping실행이 actor 사이를 넘어감contention 없으면 thread 재사용, 있으면 suspend
actor reentrancysuspend 된 일이 있어도 새 일이 진행FIFO 가 아니라서 priority 가 높은 일을 앞으로
main actor hopcooperative pool 과 main thread 사이의 전환context switch 가 필요하므로 batch 로 묶음

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

  • 작은 일을 위해 child task 나 async let 을 만들지 않는다. task 를 관리하는 비용이 얻는 이득보다 클 수 있다.
  • lock 을 쥔 채로 await 를 넘지 않고, thread-specific data 가 await 뒤에도 남아 있다고 가정하지 않는다.
  • lock 은 sync code 의 짧은 critical section 에만 쓴다. Task 를 만들고 semaphore 로 끝나기를 기다리는 code 는 쓰지 않는다.
  • 의심스러우면 scheme 에 LIBDISPATCH_COOPERATIVE_POOL_STRICT=1 을 넣고 돌려서 cooperative pool 의 thread 가 멈춰 있는지 본다.
  • loop 안에서 main actor 와 다른 actor 를 번갈아 부르고 있다면 array 단위로 한 번에 넘기도록 묶는다.
  • GCD code 를 옮길 때는 serial queue 를 actor 로, completion handler 묶음을 task group 으로 바꾸는 것부터 생각한다.

관련 글


참고자료

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