[SE-0417] Task Executor Preference
이 글은 Swift Evolution 제안서 원문과 포럼 리뷰 스레드를 Claude Code 로 정리한 글이다. 코드는 Xcode 27 의 Swift 6.4 컴파일러로 빌드하고, 진단 메시지와 실행 결과는 실제로 컴파일하고 실행해서 나온 것을 옮겼다.
제안서 정보
- 번호: SE-0417
- 상태: Implemented (Swift 6.0)
- 저자: Konrad ‘ktoso’ Malawski, John McCall, Franz Busch
- 리뷰 매니저: Doug Gregor
- pitch: Pitch: Task Executor Preference (2023-11-01 부터 11-08 까지)
- 리뷰: Review (2023-12-14 시작, 12-26 까지 예정이었고 2024-01-23 까지 연장)
- 수락: Accepted (2024-01-29)
- 이 글에서 함께 다루는 제안서: SE-0523 (Hashable conformance for UnownedTaskExecutor)
- 상태: Implemented (Swift 6.4)
- 저자: Fabian Fett, Konrad Malawski
- 리뷰 매니저: John McCall
- 구현: swiftlang/swift#73968
- pitch: Pitch: Hashable conformance for UnownedTaskExecutor (2026-03-04 부터 03-25 까지)
- 리뷰: Review (2026-03-25 부터 04-06 까지)
- 수락: Accepted (2026-04-09)
한 줄 요약
task 가 돌 곳을 actor 와 상관없이 task 단위로 정할 수 있게 된다. Task(executorPreference:) 나 withTaskExecutorPreference 로 TaskExecutor 를 지정하면, actor isolation 이 없는 비동기 코드와 그 아래 child task 가 그 executor 에서 돈다. 이 선호는 structured concurrency 의 child 로만 내려가고 Task {} 나 Task.detached 는 따라가지 않는다. 같은 글에서 SE-0523 을 함께 다룬다. 현재 task 의 선호를 UnownedTaskExecutor 로 읽을 수 있는데, 이 값을 딕셔너리 키로 쓸 수 있게 Hashable 을 더한 제안서다. 이 글은 선호가 어디까지 따라가고 어디서 끊기는지, 수명은 어떻게 되는지, 이전 OS 에서 무엇이 막히는지를 컴파일해서 실행한 출력으로 정리한다.
어떤 문제였나
Swift concurrency 에서 async 함수가 어느 스레드에서 도는지는 코드를 쓰는 쪽이 정하지 않는다. actor 에 isolated 된 코드는 그 actor 의 executor 에서 돌고, actor 가 없는 비동기 코드는 런타임이 가진 하나의 global concurrent executor 에서 돈다. 이 global executor 는 OS 가 정한 스레드 풀이고, 앱이 바꿀 수 없다.
그런데 이 풀을 쓰고 싶지 않은 경우가 있다. 서버 쪽 코드가 가장 대표적이다. 네트워크 라이브러리는 자기가 가진 이벤트 루프 스레드에서 연결을 처리하고 싶고, 그 스레드에서 돌아야 context switch 가 줄어든다. 블로킹 IO 를 부르는 코드를 공용 풀에서 돌리면 풀의 스레드를 붙잡아서 다른 task 를 굶긴다. 이럴 때 쓸 수 있는 도구가 SE-0338 의 “actor 가 아닌 비동기 함수는 global executor 에서 돈다” 는 규칙 하나뿐이라서, 라이브러리들은 아예 global executor 를 갈아 끼우는 방법까지 썼다.
갈아 끼우는 방법의 한계
pitch 스레드에서 johannesweiss 는 SwiftNIO 가 이 때문에 global executor 를 통째로 바꿔야 했다고 말했다(#10, 2023-11-02). 그 작업이 NIO 의 PR #2564 이고, 이 제안서가 들어오면 그럴 필요가 없다는 것이 그의 요지였다. global executor 를 바꾸면 프로세스 전체가 바뀐다. 한 라이브러리의 사정이 같은 프로세스의 다른 코드에 그대로 번진다.
필요한 것은 프로세스 전체가 아니라 코드 한 덩어리 단위로 “이 일은 저 executor 에서 해라” 를 말하는 방법이다. actor 의 executor 를 바꾸는 방법(SE-0392 의 custom actor executor)은 있지만, 그것은 actor 를 새로 정의해야 하고 isolation 까지 따라온다. isolation 은 필요 없고 스레드만 바꾸고 싶은 경우에는 무겁다.
해법의 뼈대
제안서는 TaskExecutor 라는 새 프로토콜을 만들고, task 마다 “선호하는 executor” 를 붙인다. 이름이 preference 인 이유가 있다. 제안서는 이 값을 “hint” 라고 쓰고, ktoso 도 리뷰에서 강한 요구가 아니고 task tree 전체에 영향을 주기 때문에 preference 라는 이름을 골랐다고 설명했다(리뷰 #33). 선호는 지켜 달라는 부탁이지 어길 수 없는 규칙이 아니다. actor 의 isolation 처럼 반드시 지켜야 하는 요구가 있으면 그쪽이 이긴다. 즉 executor 가 결정되는 순서에서 actor 가 앞이고, 그 다음이 task 의 preference 이고, 마지막이 global executor 다. 이 글에서는 이 순서가 어디서 어떻게 보이는지를 측정으로 확인한다.
무엇이 바뀌나
더해지는 API 는 TaskExecutor 프로토콜, Task(executorPreference:) 와 Task.detached 의 같은 파라미터, addTask(executorPreference:), withTaskExecutorPreference, globalConcurrentExecutor, UnsafeCurrentTask.unownedTaskExecutor 다. SE-0523 은 이 가운데 UnownedTaskExecutor 에 Hashable 을 더한다. 이 글은 먼저 시그니처를 SDK 에서 읽고, 다음으로 선호가 따라가는 곳과 끊기는 곳, 클로저가 시작하는 곳, NonisolatedNonsendingByDefault 모드의 차이, nil 과 global 의 차이, actor 와의 관계, 수명, 선호를 쓸 곳과 쓰지 않을 곳, 블로킹 IO, 이전 OS 에서의 제약을 본다. 마지막으로 Hashable 을 쓴 connection pool 을 측정하고 제안서가 남긴 앞으로의 방향과 다른 언어의 비슷한 도구를 짚는다.
시그니처와 SDK 에서의 모양
Swift 6.4 SDK 의 _Concurrency.swiftinterface 에서 핵심 선언을 옮겼다. 읽기 쉽도록 모듈 접두사(_Concurrency::, Swift::)만 떼었고 선언과 @available 은 원문 그대로다. TaskExecutor 는 Executor 를 확장하는 프로토콜이고 macOS 15 부터다.
1
2
3
4
5
6
7
8
9
10
11
12
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
public protocol TaskExecutor : Executor {
@_nonoverride func enqueue(_ job: UnownedJob)
@available(*, deprecated, message: "Implement 'enqueue(_: consuming ExecutorJob)' instead")
@_nonoverride func enqueue(_ job: consuming Job)
@_nonoverride func enqueue(_ job: consuming ExecutorJob)
func asUnownedTaskExecutor() -> UnownedTaskExecutor
}
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
public var globalConcurrentExecutor: any TaskExecutor { get }
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
public func withTaskExecutorPreference<T, Failure>(_ taskExecutor: (any TaskExecutor)?, isolation: isolated (any Actor)? = #isolation, operation: () async throws(Failure) -> T) async throws(Failure) -> T where Failure : Error
deprecated 인 것은 enqueue(_ job: consuming Job) 이고 메시지가 Implement 'enqueue(_: consuming ExecutorJob)' instead 다. 세 enqueue 는 macOS 14 의 Executor 확장에 서로를 부르는 기본 구현이 있어서, 새로 만드는 executor 는 enqueue(_ job: consuming ExecutorJob) 하나만 구현하면 된다. asUnownedTaskExecutor() 도 TaskExecutor 확장에 기본 구현이 있다.
UnownedTaskExecutor 는 @unsafe @frozen 구조체로 Sendable 이다. executor 를 retain 하지 않는 “참조” 라는 뜻이다.
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
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
@unsafe @frozen public struct UnownedTaskExecutor : Sendable {
@inlinable public init<E>(ordinary executor: __shared E) where E : TaskExecutor
@available(anyAppleOS 26.4, *)
@inlinable public init<E>(_ executor: __shared E) where E : TaskExecutor
@available(anyAppleOS 26.4, *)
public func asTaskExecutor() -> (any TaskExecutor)?
}
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
extension UnownedTaskExecutor : Equatable {
@inlinable public static func == (lhs: UnownedTaskExecutor, rhs: UnownedTaskExecutor) -> Bool {
unsafeBitCast(lhs.executor, to: (Int, Int).self) == unsafeBitCast(rhs.executor, to: (Int, Int).self)
}
}
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
extension UnownedTaskExecutor {
@_alwaysEmitIntoClient public func hash(into hasher: inout Hasher) {
let (ident, impl) = unsafeBitCast(self.executor, to: (Int, Int).self)
hasher.combine(ident)
hasher.combine(impl)
}
}
@available(anyAppleOS 27.0, *)
extension UnownedTaskExecutor : Hashable {
public var hashValue: Int { get }
}
읽을 곳이 몇 군데 있다. init(ordinary:) 는 macOS 15 부터이고 init(_:) 와 asTaskExecutor() 는 anyAppleOS 26.4 부터다. asTaskExecutor() 의 반환은 (any TaskExecutor)? 라서 옵셔널이다. == 는 별도 Equatable 확장에 있고 두 단어를 unsafeBitCast 로 비교한다. hash(into:) 는 macOS 15 확장에서 @_alwaysEmitIntoClient 로 나가고, Hashable 과 hashValue 만 anyAppleOS 27.0 이다. 이 글의 SE-0523 부분이 다루는 것이 이 마지막 확장이다.
현재 task 의 선호를 읽는 API 는 UnsafeCurrentTask.unownedTaskExecutor: UnownedTaskExecutor? 이고, task 를 만드는 쪽은 Task.init(name:executorPreference:priority:operation:) 다. runSynchronously 는 job 을 executor 의 스레드에서 직접 돌리는 메서드인데, UnownedJob 과 ExecutorJob 에 runSynchronously(on:) 와 runSynchronously(isolatedTo:taskExecutor:) 가 있다. 뒤쪽은 serial executor 와 task executor 를 한 번에 알려 주는 형태다.
TaskExecutor 프로토콜
TaskExecutor는 task 가 돌 스레드를 공급하는 프로토콜이다. SerialExecutor 가 “한 번에 하나만 돈다” 는 상호 배제를 주는 것과 달리, TaskExecutor 는 동시에 여러 job 이 돌아도 되는 “스레드의 출처” 에 가깝다. 구현하는 쪽은 enqueue 로 받은 job 을 자기 스레드에서 runSynchronously(on:) 로 돌리면 된다.
UnownedTaskExecutor
UnownedTaskExecutor는 TaskExecutor 를 retain 없이 가리키는 값이다. Task 가 자기 선호를 기억하거나, unownedTaskExecutor 가 현재 선호를 돌려줄 때 이 타입으로 준다. 수명을 책임지지 않으니 unsafe 가 붙어 있다.
withTaskExecutorPreference
withTaskExecutorPreference는 지정한 범위 안에서만 선호를 바꾸는 함수다. Task(executorPreference:) 가 새 task 를 만드는 것과 달리 현재 task 에서 범위만 잡는다. 범위가 끝나면 원래 선호로 돌아온다.
globalConcurrentExecutor
globalConcurrentExecutor는 런타임의 global concurrent executor 를 any TaskExecutor 로 꺼낸 전역 값이다. 이 값을 선호로 주면 “이 범위는 공용 풀로 돌려라” 가 된다.
선호가 따라가는 곳과 끊기는 곳
17 가지를 한 파일에서 찍었다. executor 는 DispatchQueue 를 감싼 QueueTaskExecutor 이고, DispatchSpecificKey 로 현재 스레드가 어느 executor 의 큐에서 도는지를 읽는다. 큐에 속하지 않으면 “global pool” 로 찍는다. 코드는 길어서 key 와 pad 같은 보조 선언은 접고 핵심만 싣는다.
Prefs.swift
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
final class QueueTaskExecutor: TaskExecutor {
let queue: DispatchQueue
let name: String
init(_ name: String) {
self.name = name
queue = DispatchQueue(label: name, attributes: .concurrent)
queue.setSpecific(key: key, value: name)
}
func enqueue(_ job: consuming ExecutorJob) {
let job = UnownedJob(job)
queue.async { job.runSynchronously(on: self.asUnownedTaskExecutor()) }
}
}
func whereAmI() -> String { DispatchQueue.getSpecific(key: key) ?? "global pool" }
func nonisolatedAsync(_ label: String) async { print(label.pad, whereAmI()) }
@concurrent func concurrentAsync(_ label: String) async { print(label.pad, whereAmI()) }
actor DefaultActor { func hello(_ label: String) { print(label.pad, whereAmI()) } }
let io = QueueTaskExecutor("io-executor")
let other = QueueTaskExecutor("other-executor")
@main struct M {
static func main() async {
DispatchQueue.main.setSpecific(key: key, value: "main thread")
await nonisolatedAsync("1 no preference")
await Task(executorPreference: io) {
await nonisolatedAsync("2 Task(executorPreference:) body")
await concurrentAsync("3 @concurrent func")
await DefaultActor().hello("4 default actor method")
await MainActor.run { print("5 MainActor.run".pad, whereAmI(), "isMain:", MainActor.assumeIsolated { true }) }
async let a: Void = nonisolatedAsync("6 async let")
await a
await withTaskGroup(of: Void.self) { g in
g.addTask { await nonisolatedAsync("7 addTask") }
g.addTask(executorPreference: nil) { await nonisolatedAsync("8 addTask(pref: nil)") }
g.addTask(executorPreference: other) { await nonisolatedAsync("9 addTask(pref: other)") }
g.addTask(executorPreference: globalConcurrentExecutor) { await nonisolatedAsync("10 addTask(pref: global)") }
}
await Task { await nonisolatedAsync("11 Task {} inside") }.value
await Task.detached { await nonisolatedAsync("12 Task.detached inside") }.value
await withTaskExecutorPreference(globalConcurrentExecutor) { await nonisolatedAsync("13 withPref(global)") }
await withTaskExecutorPreference(nil) { await nonisolatedAsync("14 withPref(nil)") }
}.value
await withTaskExecutorPreference(other) {
print("15 withPref(other) closure".pad, whereAmI())
await nonisolatedAsync("16 inside withPref(other)")
}
await nonisolatedAsync("17 after withPref")
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1 no preference global pool
2 Task(executorPreference:) body io-executor
3 @concurrent func io-executor
4 default actor method io-executor
5 MainActor.run main thread isMain: true
6 async let io-executor
7 addTask io-executor
8 addTask(pref: nil) io-executor
9 addTask(pref: other) other-executor
10 addTask(pref: global) global pool
11 Task {} inside global pool
12 Task.detached inside global pool
13 withPref(global) global pool
14 withPref(nil) io-executor
15 withPref(other) closure main thread
16 inside withPref(other) other-executor
17 after withPref global pool
bash diag.sh Prefs.swift 는 [exit 0] 이고 위 17 줄은 실행 결과다. 7 번부터 10 번까지 네 줄은 실행마다 순서가 바뀐다. 같은 task group 에 addTask 네 개를 넣기 때문에 서로 다른 executor 에서 동시에 돌고, 어느 줄이 먼저 찍히느냐는 스케줄링에 달렸다. 이번 측정에서는 50 번 중 여섯 가지 순서가 나왔고 “7 8 9 10” 이 27 번으로 가장 많았다. 순서와 횟수는 머신과 부하에 따라 달라지는 값이다. 변하지 않은 것은 줄의 내용이어서, 50 번 모두 같은 executor 이름이 찍혔다. 1 번부터 6 번, 11 번부터 17 번은 순서와 내용이 50 번 모두 같았다.
읽는 법은 이렇다.
- 1 번은 선호가 없을 때의 기본이다. global pool 에서 돈다.
- 2 번부터 4 번까지가 선호의 기본 효과다. 선호를 준
Task의 본문,@concurrent함수, default actor 의 메서드가 전부 io-executor 에서 돈다. default actor 는 자기 executor 가 따로 없어서 선호를 따라간다. - 5 번의
MainActor.run은 main thread 에서 돈다. 선호가 있어도 MainActor 는 자기 executor 를 따로 가지고 있어서 선호를 따르지 않는다.main thread라는 글자는DispatchQueue.main에 달아 둔DispatchSpecificKey의 값이고, 판정은 이 key 를 읽어서 한다. 줄 끝의isMain: true는MainActor.assumeIsolated { true }의 값이다. 이 호출은 MainActor 가 아니면false를 돌려주는 것이 아니라 실패하면 trap 하므로true외의 값이 나올 수 없고, 돌아왔다는 사실이 MainActor 위라는 증거다. - 6 번부터 8 번까지는 child task 다.
async let, 그냥addTask,executorPreference: nil을 준addTask가 모두 io-executor 다.nil은 “선호를 따로 주지 않는다” 이고, 바깥의 선호를 그대로 물려받는다. - 9 번과 10 번은 child 에 명시한 경우다. other 를 주면 other-executor 에서,
globalConcurrentExecutor를 주면 global pool 에서 돈다. - 11 번과 12 번은
Task {}와Task.detached다. 둘 다 global pool 이다. unstructured task 는 부모의 선호를 물려받지 않는다. - 13 번의
withTaskExecutorPreference(globalConcurrentExecutor)는 범위 안에서 선호를 global 로 되돌린다. 14 번의withTaskExecutorPreference(nil)은 아무것도 바꾸지 않아 바깥의 io 를 그대로 쓴다. - 15 번의 클로저 본문 첫 줄은 main thread 에서 찍힌다.
@main static func main()이 MainActor 에 isolated 되어 있고,withTaskExecutorPreference는isolation: isolated (any Actor)? = #isolation으로 호출한 쪽의 isolation 을 클로저가 이어받기 때문이다. isolation 이 선호보다 앞서므로 클로저가 시작하는 줄은 MainActor 에서 돈다. 다음 절에서#isolation을 찍어 확인한다. 16 번은 그 안에서 부른 nonisolated 비동기 함수라서 other-executor 로 간다. 이 설명은 기본 모드에서 그렇다는 것이고, 모드를 바꾸면 달라진다(그 다음 절). - 17 번은 범위를 벗어난 뒤라서 선호가 없고 global pool 로 돌아온다.
실선은 선호를 따라가는 경로이고 점선은 끊기는 경로다. 어디서 끊기는지에는 규칙이 있다. 선호는 structured concurrency 의 부모와 자식 관계로만 내려가고, 새로 시작하는 unstructured task 와 자기 executor 를 가진 isolation 은 선호를 보지 않는다. 이 규칙이 왜 이렇게 그어졌는지는 아래 스레드 절에서 정리한다.
withTaskGroup 은 child task 를 묶는 API 이고, addTask 는 그 group 에 child 를 더하는 메서드다. @concurrent 는 nonisolated 비동기 함수가 호출한 쪽의 actor 를 벗어나서 돌게 하는 표시다. 어느 executor 로 갈지를 정하는 것은 아니라서, 선호가 있으면 3 번처럼 그 executor 로 가고 선호가 없을 때만 공용 풀로 간다. 셋 다 이 글에서는 선호가 child 에 닿는지 보려고 썼다.
클로저가 시작하는 곳
앞의 15 번은 withTaskExecutorPreference(other) 의 클로저인데도 main thread 에서 시작했다. 이유를 WithPrefIso.swift 로 가렸다. iso() 는 #isolation 을 기본 인자로 받아 지금 코드가 isolated 된 actor 의 타입 이름을 찍고, 없으면 nil 을 찍는다. pthread_main_np() 는 지금 스레드가 프로세스의 main thread 이면 1 을 돌려준다. QE 와 key, whereAmI 는 Prefs.swift 와 같은 모양이라 줄였다.
WithPrefIso.swift
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
func iso(_ i: isolated (any Actor)? = #isolation) -> String { i.map { "\(type(of: $0))" } ?? "nil" }
let other = QE("other-executor")
let io = QE("io-executor")
@main struct M {
static func main() async {
DispatchQueue.main.setSpecific(key: key, value: "main queue")
print("A main() #isolation:", iso(), whereAmI(), "pthread_main:", pthread_main_np())
try? await Task.sleep(for: .milliseconds(10))
print("B main() after suspension:", iso(), whereAmI(), "pthread_main:", pthread_main_np())
await withTaskExecutorPreference(other) {
print("C closure from main():", iso(), whereAmI(), "pthread_main:", pthread_main_np())
}
await Task(executorPreference: io) {
await withTaskExecutorPreference(other) {
print("D closure from nonisolated task(io):", iso(), whereAmI())
}
}.value
await Task.detached {
await withTaskExecutorPreference(other) {
print("E closure from detached nonisolated:", iso(), whereAmI())
}
}.value
}
}
1
2
3
4
5
A main() #isolation: MainActor main queue pthread_main: 1
B main() after suspension: MainActor main queue pthread_main: 1
C closure from main(): MainActor main queue pthread_main: 1
D closure from nonisolated task(io): nil other-executor
E closure from detached nonisolated: nil other-executor
xcrun swiftc -parse-as-library -wmo -swift-version 6 로 컴파일해 3 번 돌렸고 출력은 같았다.
- A 와 B 는
main()자체의 isolation 이다.@main static func main()은 MainActor 에 isolated 라서#isolation이MainActor이고 main thread 다. 중간에Task.sleep으로 suspend 했다 돌아와도 같다. - C 의 클로저는
main()의 isolation 을 이어받아서 선호가 other 인데도 MainActor 에서 시작한다.withTaskExecutorPreference의isolation: isolated (any Actor)? = #isolation이 호출한 쪽의 isolation 을 그대로 쓰기 때문이다. isolation 이 선호보다 앞선다는 것이 이 줄이다. - D 와 E 는 nonisolated 인
Task(executorPreference:)와Task.detached안에서 불렀다.#isolation이nil이고 클로저는 other-executor 에서 돈다.
15 번이 main thread 였던 것은 #isolation 자체가 아니라 main() 이 MainActor 라서다. nonisolated 인 곳에서 불렀다면 15 번도 other-executor 였을 것이다.
NonisolatedNonsendingByDefault 모드의 차이
Swift 6.4 의 기본 모드에서는 nonisolated 비동기 함수가 호출한 쪽의 actor 를 떠나 선호한 executor 나 공용 풀로 간다. SE-0461 의 upcoming feature NonisolatedNonsendingByDefault 를 켜면 nonisolated 비동기 함수가 호출한 쪽의 actor 에 남는다. 앞의 Prefs.swift 를 -enable-upcoming-feature NonisolatedNonsendingByDefault 를 더해 컴파일하고 돌렸다.
1
2
3
1 no preference main thread
16 inside withPref(other) main thread
17 after withPref main thread
17 줄 가운데 달라진 것은 이 세 줄이다. 나머지는 기본 모드와 같았다(7 번부터 10 번의 순서는 여전히 실행마다 바뀐다). 1 번, 16 번, 17 번은 모두 MainActor 위의 main() 에서 부른 nonisolated 비동기 함수다. nonsending 모드에서는 이런 함수가 호출한 쪽 actor 에 남으므로 선호가 있든(16 번) 없든(1 번, 17 번) main thread 에서 돈다. 선호보다 isolation 이 먼저라는 규칙이 같은 모양으로 드러난다.
이 때문에 앞의 두 설명은 기본 모드를 전제로 한다. 16 번에서 withTaskExecutorPreference(other) 안의 비동기 함수가 other-executor 로 간다는 것, 그리고 이 글의 블로킹 IO 절에서 기대하는 효과가 그렇다. 같은 코드를 nonsending 모드로 돌리면 클로저 안에서 부른 nonisolated 비동기 함수는 호출한 actor 에 남는다.
선호를 준 Task 의 isolation
선호를 주고 시작한 Task 는 호출한 쪽의 actor isolation 을 물려받지 않는다. TaskPrefIso.swift 의 두 Task 가 같은 @MainActor 변수를 고친다.
TaskPrefIso.swift
1
2
3
4
5
6
@MainActor var counter = 0
final class QE: TaskExecutor { func enqueue(_ job: consuming ExecutorJob) {} }
@MainActor func f(_ e: QE) {
Task { counter += 1 }
Task(executorPreference: e) { counter += 1 }
}
1
2
3
4
5
6
7
8
9
10
11
12
TaskPrefIso.swift:5:33: error: main actor-isolated var 'counter' can not be mutated from a nonisolated context
1 | @MainActor var counter = 0
| `- note: mutation of this var is only permitted within the actor
2 | final class QE: TaskExecutor { func enqueue(_ job: consuming ExecutorJob) {} }
3 | @MainActor func f(_ e: QE) {
4 | Task { counter += 1 }
5 | Task(executorPreference: e) { counter += 1 }
| |- error: main actor-isolated var 'counter' can not be mutated from a nonisolated context
| `- note: consider declaring an isolated method on 'MainActor' to perform the mutation
6 | }
7 |
[exit 1]
bash diag.sh TaskPrefIso.swift 의 결과다. 4 번 줄의 Task { } 는 진단이 없고 5 번 줄만 걸린다. Task { } 의 클로저는 @MainActor 인 f 의 isolation 을 이어받지만, Task(executorPreference:) 의 operation 에는 그 상속이 없어서 nonisolated 로 취급된다. 앞의 John_McCall 의 구분처럼 isolation 은 정적이고 선호는 동적이다. 그래서 선호를 주면서 MainActor 의 변수를 만지려면 클로저에 @MainActor in 을 직접 적어야 한다. Task(executorPreference: e) { @MainActor in counter += 1 } 은 같은 파일 형식으로 진단 없이 통과했다(MainIsoOK.swift).
nil 과 globalConcurrentExecutor 의 차이
addTask(executorPreference: nil) 은 바깥 선호를 이어받고, globalConcurrentExecutor 는 공용 풀로 되돌린다. 이 둘이 다르다는 것은 앞의 8 번과 10 번이 보였다. 선호를 읽는 쪽에서도 같은지 UnsafeCurrentTask 로 읽어 보았다.
Unowned.swift
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
27
28
29
final class QE: TaskExecutor {
let q = DispatchQueue(label: "qe", attributes: .concurrent)
func enqueue(_ job: consuming ExecutorJob) {
let j = UnownedJob(job)
q.async { j.runSynchronously(on: self.asUnownedTaskExecutor()) }
}
}
func current() -> UnownedTaskExecutor? { withUnsafeCurrentTask { $0?.unownedTaskExecutor } }
let io = QE()
@main struct M {
static func main() async {
print("no preference:", current() == nil ? "nil" : "some")
await Task(executorPreference: io) {
let u = current()
print("in io task: equals io =", u == io.asUnownedTaskExecutor())
print("global equals io =", globalConcurrentExecutor.asUnownedTaskExecutor() == io.asUnownedTaskExecutor())
await withTaskExecutorPreference(globalConcurrentExecutor) {
print("withPref(global): current == global =", current() == globalConcurrentExecutor.asUnownedTaskExecutor())
}
await withTaskExecutorPreference(nil) {
print("withPref(nil): still io =", current() == io.asUnownedTaskExecutor())
}
}.value
print("globalConcurrentExecutor type:", type(of: globalConcurrentExecutor))
}
}
1
2
3
4
5
6
no preference: nil
in io task: equals io = true
global equals io = false
withPref(global): current == global = true
withPref(nil): still io = true
globalConcurrentExecutor type: DispatchGlobalTaskExecutor
bash diag.sh Unowned.swift 는 [exit 0] 이고 위 여섯 줄은 8 번 돌려도 같았다. 선호가 없으면 unownedTaskExecutor 는 nil 이다. 선호를 주면 io 와 같은 값이 나온다. withTaskExecutorPreference(globalConcurrentExecutor) 안에서는 nil 이 아니라 global executor 의 값이 나온다. 선호가 없음(nil)과 global 을 선호함은 읽는 값도 다르다. withTaskExecutorPreference(nil) 은 바깥 값을 그대로 둔다.
마지막 줄이 보여 주는 것은 globalConcurrentExecutor 의 실제 타입이다. 이 SDK 에서는 DispatchGlobalTaskExecutor 다.
UnsafeCurrentTask 와 withUnsafeCurrentTask
withUnsafeCurrentTask는 지금 돌고 있는 task 를 UnsafeCurrentTask 로 빌려 주는 함수다. UnsafeCurrentTask는 task 의 수명에 묶여 있어서, 이 값을 클로저 밖으로 들고 나가면 안 된다. unownedTaskExecutor 가 이 타입에만 있는 이유를 ktoso 는 lifetime 때문이라고 설명했다(#28, 2023-11-08). 스레드 절에서 다시 본다.
actor 와의 우선순위
선호와 actor 가 같이 있으면 누가 이기는지를 Actors.swift 로 보았다. Both 는 SerialExecutor 이면서 TaskExecutor 인 타입이고, runSynchronously(isolatedTo:taskExecutor:) 로 두 역할을 한 번에 알려 준다.
Actors.swift
QE 는 Prefs.swift 의 executor 와 같은 모양이고, SerialOnly 는 Both 에서 TaskExecutor 를 뺀 serial executor 다. 둘 다 이름만 달리 찍는다.
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
final class Both: SerialExecutor, TaskExecutor {
let q: DispatchQueue
init() { q = DispatchQueue(label: "both"); q.setSpecific(key: key, value: "both-executor") }
func enqueue(_ job: consuming ExecutorJob) {
let j = UnownedJob(job)
q.async { j.runSynchronously(isolatedTo: self.asUnownedSerialExecutor(), taskExecutor: self.asUnownedTaskExecutor()) }
}
func asUnownedSerialExecutor() -> UnownedSerialExecutor { UnownedSerialExecutor(ordinary: self) }
}
actor Default { func hi(_ s: String) { print(s, whereAmI()) } }
actor Custom {
let ex = SerialOnly()
nonisolated var unownedExecutor: UnownedSerialExecutor { ex.asUnownedSerialExecutor() }
func hi(_ s: String) { print(s, whereAmI()) }
}
actor OnBoth {
let ex: Both
init(_ e: Both) { ex = e }
nonisolated var unownedExecutor: UnownedSerialExecutor { ex.asUnownedSerialExecutor() }
func hi(_ s: String) async {
print(s, whereAmI())
await nonisolatedAsync(" nonisolated call from OnBoth")
}
}
@main struct M {
static func main() async {
let io = QE("io-executor")
let both = Both()
await Task(executorPreference: io) {
await Default().hi("default actor:")
await Custom().hi("custom-executor actor:")
}.value
await Default().hi("default actor, no preference:")
await OnBoth(both).hi("actor on Both, no preference:")
await Task(executorPreference: both) {
await nonisolatedAsync("Task(pref: both) nonisolated:")
await Default().hi("Task(pref: both) default actor:")
}.value
}
}
1
2
3
4
5
6
7
default actor: io-executor
custom-executor actor: serial-executor
default actor, no preference: global pool
actor on Both, no preference: both-executor
nonisolated call from OnBoth global pool
Task(pref: both) nonisolated: both-executor
Task(pref: both) default actor: both-executor
bash diag.sh Actors.swift 는 [exit 0] 이고 위 일곱 줄은 20 번 돌려도 같았다.
- default actor 는 선호가 있으면 io-executor 에서, 없으면 global pool 에서 돈다. default actor 의 executor 는 선호를 따라가는 쪽이다.
- 자기
unownedExecutor를 가진 actor(Custom)는 선호가 io 여도 serial-executor 에서 돈다. actor 가 이긴다. OnBoth는Both를 actor 의 executor 로 쓰는 actor 다. 선호 없이 불러도 both-executor 에서 돌지만, 그 안에서 부른 nonisolated 비동기 함수는 global pool 로 나간다. actor 의 executor 가TaskExecutor이기도 하다고 해서 task 의 선호가 되는 것은 아니다. isolation 으로 돌 때는 serial executor 이고, 선호로서의 task executor 는 task 에 따로 붙어야 한다.- 반대로
Task(executorPreference: both)에서는 nonisolated 함수도 default actor 도 both-executor 에서 돈다.Both를 선호로 주면 선호가 따라가는 모든 곳에서 쓰인다.
이 우선순위는 제안서가 말하는 규칙과 같다. 반드시 그 executor 에서 돌아야 하는 요구가 있으면 요구가 이기고, 요구가 없으면 선호가 따라간다. pitch 에서 ktoso 는 default actor 의 executor 는 TaskExecutor 로 노출되지 않는다고 답했다(#3, 2023-11-01). 위 Custom 과 OnBoth 의 결과는 actor 의 executor 와 task 의 선호가 서로 다른 축이라는 것을 보인다.
SerialExecutor 단독 선호의 컴파일 에러
SerialExecutor 만 구현한 타입을 선호로 넘기면 컴파일 에러다.
Serial.swift
1
2
3
4
final class S: SerialExecutor {
func enqueue(_ job: consuming ExecutorJob) {}
}
func f() { Task(executorPreference: S()) {} }
1
2
3
4
5
6
7
Serial.swift:4:37: error: argument type 'S' does not conform to expected type 'TaskExecutor'
2 | func enqueue(_ job: consuming ExecutorJob) {}
3 | }
4 | func f() { Task(executorPreference: S()) {} }
| `- error: argument type 'S' does not conform to expected type 'TaskExecutor'
5 |
[exit 1]
SerialExecutor 는 상호 배제를 약속하는 프로토콜이라 “스레드를 공급한다” 는 TaskExecutor 와 다른 약속이다. 두 역할을 다 하고 싶은 타입은 앞의 Both 처럼 둘 다 채택한다.
두 역할을 겸하는 executor
한 타입이 SerialExecutor 와 TaskExecutor 를 둘 다 채택할 수도 있다(제안서 1.5 에서 문서화됐다). 이때는 SerialExecutor 의 의미, 곧 job 을 동시에 돌리지 않는다는 약속을 반드시 지켜야 한다. 그 executor 가 actor 의 isolation 컨텍스트로도 쓰일 수 있기 때문이다. 앞의 Both 는 직렬 DispatchQueue 위에 만들어서 이 약속을 지킨다. Prefs.swift 의 QueueTaskExecutor 는 .concurrent 큐라서 선호로는 쓸 수 있어도 SerialExecutor 까지 겸하게 만들면 안 된다.
executor 의 수명
선호를 준 task 는 그 executor 를 자기가 끝날 때까지 붙잡아 둔다. Lifetime.swift 는 executor 를 do {} 블록 안에서만 만들고, 밖에서는 참조를 놓은 채 task 를 기다린다.
Lifetime.swift
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 QE: TaskExecutor {
let q = DispatchQueue(label: "life", attributes: .concurrent)
init() { print("executor init") }
deinit { print("executor deinit") }
func enqueue(_ job: consuming ExecutorJob) {
let j = UnownedJob(job)
q.async { j.runSynchronously(on: self.asUnownedTaskExecutor()) }
}
}
@main struct M {
static func main() async {
let t: Task<Void, Never>
do {
t = Task(executorPreference: QE()) {
try? await Task.sleep(for: .milliseconds(100))
print("task body after sleep")
}
}
print("local reference gone")
await t.value
print("task finished")
try? await Task.sleep(for: .milliseconds(50))
print("end")
}
}
1
2
3
4
5
6
executor init
local reference gone
task body after sleep
executor deinit
task finished
end
bash diag.sh Lifetime.swift 는 [exit 0] 이고 위 여섯 줄은 30 번 돌려도 같았다. local reference gone 이 찍혔는데도 executor deinit 은 task 본문이 끝난 뒤에 나왔다. 이름 있는 변수로 잡고 있지 않아도 task 가 executor 를 retain 한다. 그래서 “만들고 바로 넘기는” 쓰임이 안전하다.
이 성질이 withTaskExecutorPreference 에서도 같은지 WithPrefLife.swift 로 보았다. executor 를 인자 자리에서 바로 만들어 넘기고, 범위 안에서 100 밀리초를 잔다.
WithPrefLife.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
final class QE: TaskExecutor {
let q = DispatchQueue(label: "life", attributes: .concurrent)
init() { print("executor init") }
deinit { print("executor deinit") }
func enqueue(_ job: consuming ExecutorJob) {
let j = UnownedJob(job)
q.async { j.runSynchronously(on: self.asUnownedTaskExecutor()) }
}
}
func work() async { try? await Task.sleep(for: .milliseconds(100)); print("inside scope after sleep") }
@main struct M {
static func main() async {
await withTaskExecutorPreference(QE()) {
print("scope start")
await work()
}
print("scope ended")
try? await Task.sleep(for: .milliseconds(50))
print("end")
}
}
1
2
3
4
5
6
executor init
scope start
inside scope after sleep
executor deinit
scope ended
end
3 번 돌려도 같았다. executor deinit 이 범위 안의 작업이 끝난 뒤, scope ended 앞에 찍혔다. 범위 안에서는 executor 가 살아 있고, 범위를 나오면 놓는다. John_McCall 이 pitch 에서 말한 “scope 가 있는 연산 안에서만 선호를 세팅하므로 executor 를 그 시간 동안 살려 두는 것은 예측 가능한 약속” 이라는 설명이 이 출력이다(#34). 앞서 UnownedTaskExecutor 는 retain 하지 않는 값이라고 했으니, 이 값을 들고 있는 쪽이 executor 의 수명을 챙겨야 한다는 것도 같은 이야기다.
선호를 쓸 곳과 쓰지 않을 곳
선호는 어디에나 붙일 수 있다. 그래서 제안서는 “Not a Golden Hammer” 라는 절을 따로 두고 주의를 준다. 앞에서 본 것처럼 선호가 있으면 nonisolated 비동기 함수가 공용 풀로 hop 하지 않고 선호한 executor 에 남는다. 이 동작을 어디까지 쓸지가 이 절의 주제다.
과하게 붙는 문제
선호를 주면 context switch 가 줄어드는 대신 코드가 그 executor 에 붙어 있게 된다. 제안서는 이것이 바람직하지 않은 상황도 있다고 경고한다. MainActor 에 과하게 매달려 있는 것이 SE-0338 이 nonisolated 비동기 함수를 항상 호출한 쪽에서 내보내도록 바꾼 주된 이유였고, 이 제안은 특정 executor 에 대해 그 동작을 되살린다. 좋은 후보는 특정 스레드를 써서 동기화 비용을 줄이는 이벤트 루프 기반 시스템(네트워크 앱)이나, 블로킹 연산을 공용 풀 밖에서 돌려야 하는 IO 시스템이다. 문제를 충분히 이해한 뒤 sticky 동작이 이로운 코드 조각에만 적용하라는 것이 제안서의 권고다.
sticky 규칙
규칙은 둘이다. 어떤 코드에 특정 executor 에서 돌아야 한다는 엄격한 요구가 있으면 그 executor 에서 돌고 선호는 무시된다. 요구가 없으면 선호가 hop 과 context switch 를 줄인다. 앞의 5 번(MainActor)과 Custom actor 가 첫째 규칙의 예이고, 2 번부터 8 번이 둘째 규칙의 예다.
progressive disclosure
제안서는 이를 Swift 의 progressive disclosure 로 설명한다. 처음에는 context switch 를 신경 쓰지 않아도 되고, 성능 분석에서 문제로 드러났을 때 필요한 부분에만 sticky 동작을 들이면 된다. pitch 에서 wadetregaskis 는 이 흐름을 세 단계로 정리해도 되는지 물었다. 느리지 않으면 끝, 느리면 작업을 detached task 로 나누고, 그래도 느리면 TaskExecutor 로 스레드 배치를 다듬는 것이다. 그는 대부분의 Swift 사용자가 이 도구를 몰라도 되어야 한다는 점을 강조했다.
블로킹 IO 를 공용 풀 밖으로 빼기
제안서가 드는 가장 직접적인 예는 블로킹 read 를 감싸는 IO 라이브러리다. 공용 풀은 폭이 제한되어 있어서 블로킹 호출이 스레드를 붙잡으면 다른 task 가 굶는다. 제안서의 callRead 를 줄여 BlockingIO2.swift 로 돌렸다. dedicatedIO 는 Prefs.swift 의 executor 와 같은 모양이고, callReadConcurrent 는 같은 일을 @concurrent 함수 안에서 한다.
BlockingIO2.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let dedicatedIO = QE("dedicated-io")
func blockingRead() -> Int { print("blockingRead on", whereAmI()); return 1 }
func callRead() async -> Int {
print("callRead #isolation:", iso(), whereAmI())
return await withTaskExecutorPreference(dedicatedIO) { blockingRead() }
}
@concurrent func callReadConcurrent() async -> Int {
return await withTaskExecutorPreference(dedicatedIO) { blockingRead() }
}
@main struct M {
static func main() async {
DispatchQueue.main.setSpecific(key: key, value: "main queue")
_ = await callRead()
_ = await callReadConcurrent()
}
}
1
2
3
callRead #isolation: nil global pool
blockingRead on dedicated-io
blockingRead on dedicated-io
3 번 돌려도 같았다. main() 은 MainActor 지만 기본 모드에서 nonisolated 인 callRead 는 MainActor 를 벗어나 공용 풀에서 시작한다(#isolation 이 nil). 그 안의 withTaskExecutorPreference(dedicatedIO) 범위에서 blockingRead 는 dedicated-io 에서 돈다. @concurrent 인 callReadConcurrent 도 같다. 공용 풀의 스레드는 블로킹 호출을 받지 않는다.
제안서의 callBulk 는 같은 dedicatedIO 선호 안에서 callRead 를 두 번 부르는 형태다. 두 호출이 같은 스레드를 쓸 수 있어서 callBulk 가 callRead 를 부를 때도 실제 context switch 가 필요 없을 수 있다. 라이브러리 쓰는 쪽에서 라이브러리의 느린 비동기 함수를 withTaskExecutorPreference 로 감싸 별도 executor 로 빼내는 것도 같은 방법이다.
이 효과도 기본 모드 전제다. NonisolatedNonsendingByDefault 를 켜고 같은 파일을 돌리면 callRead 의 #isolation 이 MainActor 로 바뀌고 main queue 가 찍힌다. 클로저 안의 blockingRead 는 그래도 dedicated-io 에서 돌았지만, 클로저 안에서 nonisolated 비동기 함수를 부르면 앞의 16 번처럼 호출한 actor 에 남는다.
이전 OS 에서 막히는 곳
이 API 는 모두 macOS 15 부터이고, Hashable 은 27.0 부터다. Avail.swift 를 -target arm64-apple-macos14, macos15, macos26 으로 컴파일했다.
Avail.swift
1
2
3
4
5
6
7
8
9
10
11
12
final class QE: TaskExecutor {
func enqueue(_ job: consuming ExecutorJob) {}
}
func f(_ e: QE) async {
Task(executorPreference: e) {}
await withTaskExecutorPreference(e) {}
}
func g(_ a: UnownedTaskExecutor, _ b: UnownedTaskExecutor) -> Bool {
var d: [UnownedTaskExecutor: Int] = [:]
d[a] = 1
return a == b
}
macOS 14 로 컴파일하면 여덟 개가 걸린다. 진단 전체를 원문 그대로 싣는다.
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
Avail.swift:8:13: error: 'UnownedTaskExecutor' is only available in macOS 15.0 or newer
6 | await withTaskExecutorPreference(e) {}
7 | }
8 | func g(_ a: UnownedTaskExecutor, _ b: UnownedTaskExecutor) -> Bool {
| | `- error: 'UnownedTaskExecutor' is only available in macOS 15.0 or newer
| `- note: add '@available' attribute to enclosing global function
9 | var d: [UnownedTaskExecutor: Int] = [:]
10 | d[a] = 1
Avail.swift:8:39: error: 'UnownedTaskExecutor' is only available in macOS 15.0 or newer
6 | await withTaskExecutorPreference(e) {}
7 | }
8 | func g(_ a: UnownedTaskExecutor, _ b: UnownedTaskExecutor) -> Bool {
| | `- error: 'UnownedTaskExecutor' is only available in macOS 15.0 or newer
| `- note: add '@available' attribute to enclosing global function
9 | var d: [UnownedTaskExecutor: Int] = [:]
10 | d[a] = 1
Avail.swift:5:3: error: 'init(name:executorPreference:priority:operation:)' is only available in macOS 15.0 or newer
2 | func enqueue(_ job: consuming ExecutorJob) {}
3 | }
4 | func f(_ e: QE) async {
| `- note: add '@available' attribute to enclosing global function
5 | Task(executorPreference: e) {}
| |- error: 'init(name:executorPreference:priority:operation:)' is only available in macOS 15.0 or newer
| `- note: add 'if #available' version check
6 | await withTaskExecutorPreference(e) {}
7 | }
Avail.swift:6:9: error: 'withTaskExecutorPreference(_:isolation:operation:)' is only available in macOS 15.0 or newer
2 | func enqueue(_ job: consuming ExecutorJob) {}
3 | }
4 | func f(_ e: QE) async {
| `- note: add '@available' attribute to enclosing global function
5 | Task(executorPreference: e) {}
6 | await withTaskExecutorPreference(e) {}
| |- error: 'withTaskExecutorPreference(_:isolation:operation:)' is only available in macOS 15.0 or newer
| `- note: add 'if #available' version check
7 | }
8 | func g(_ a: UnownedTaskExecutor, _ b: UnownedTaskExecutor) -> Bool {
Avail.swift:9:11: error: 'UnownedTaskExecutor' is only available in macOS 15.0 or newer
6 | await withTaskExecutorPreference(e) {}
7 | }
8 | func g(_ a: UnownedTaskExecutor, _ b: UnownedTaskExecutor) -> Bool {
| `- note: add '@available' attribute to enclosing global function
9 | var d: [UnownedTaskExecutor: Int] = [:]
| |- error: 'UnownedTaskExecutor' is only available in macOS 15.0 or newer
| `- note: add 'if #available' version check
10 | d[a] = 1
11 | return a == b
Avail.swift:9:39: error: conformance of 'UnownedTaskExecutor' to 'Hashable' is only available in macOS 27.0 or newer
6 | await withTaskExecutorPreference(e) {}
7 | }
8 | func g(_ a: UnownedTaskExecutor, _ b: UnownedTaskExecutor) -> Bool {
| `- note: add '@available' attribute to enclosing global function
9 | var d: [UnownedTaskExecutor: Int] = [:]
| |- error: conformance of 'UnownedTaskExecutor' to 'Hashable' is only available in macOS 27.0 or newer
| `- note: add 'if #available' version check
10 | d[a] = 1
11 | return a == b
Avail.swift:10:3: error: conformance of 'UnownedTaskExecutor' to 'Hashable' is only available in macOS 27.0 or newer
6 | await withTaskExecutorPreference(e) {}
7 | }
8 | func g(_ a: UnownedTaskExecutor, _ b: UnownedTaskExecutor) -> Bool {
| `- note: add '@available' attribute to enclosing global function
9 | var d: [UnownedTaskExecutor: Int] = [:]
10 | d[a] = 1
| |- error: conformance of 'UnownedTaskExecutor' to 'Hashable' is only available in macOS 27.0 or newer
| `- note: add 'if #available' version check
11 | return a == b
12 | }
Avail.swift:11:12: error: conformance of 'UnownedTaskExecutor' to 'Equatable' is only available in macOS 15.0 or newer
6 | await withTaskExecutorPreference(e) {}
7 | }
8 | func g(_ a: UnownedTaskExecutor, _ b: UnownedTaskExecutor) -> Bool {
| `- note: add '@available' attribute to enclosing global function
9 | var d: [UnownedTaskExecutor: Int] = [:]
10 | d[a] = 1
11 | return a == b
| |- error: conformance of 'UnownedTaskExecutor' to 'Equatable' is only available in macOS 15.0 or newer
| `- note: add 'if #available' version check
12 | }
13 |
[exit 1]
macOS 15 와 26 으로 컴파일하면 에러가 세 개로 줄고 전부 Hashable 이다. 두 타깃의 출력은 같았다.
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
27
28
29
30
31
32
33
34
Avail.swift:9:7: error: conformance of 'UnownedTaskExecutor' to 'Hashable' is only available in macOS 27.0 or newer
6 | await withTaskExecutorPreference(e) {}
7 | }
8 | func g(_ a: UnownedTaskExecutor, _ b: UnownedTaskExecutor) -> Bool {
| `- note: add '@available' attribute to enclosing global function
9 | var d: [UnownedTaskExecutor: Int] = [:]
| |- error: conformance of 'UnownedTaskExecutor' to 'Hashable' is only available in macOS 27.0 or newer
| `- note: add 'if #available' version check
10 | d[a] = 1
11 | return a == b
Avail.swift:9:39: error: conformance of 'UnownedTaskExecutor' to 'Hashable' is only available in macOS 27.0 or newer
6 | await withTaskExecutorPreference(e) {}
7 | }
8 | func g(_ a: UnownedTaskExecutor, _ b: UnownedTaskExecutor) -> Bool {
| `- note: add '@available' attribute to enclosing global function
9 | var d: [UnownedTaskExecutor: Int] = [:]
| |- error: conformance of 'UnownedTaskExecutor' to 'Hashable' is only available in macOS 27.0 or newer
| `- note: add 'if #available' version check
10 | d[a] = 1
11 | return a == b
Avail.swift:10:3: error: conformance of 'UnownedTaskExecutor' to 'Hashable' is only available in macOS 27.0 or newer
6 | await withTaskExecutorPreference(e) {}
7 | }
8 | func g(_ a: UnownedTaskExecutor, _ b: UnownedTaskExecutor) -> Bool {
| `- note: add '@available' attribute to enclosing global function
9 | var d: [UnownedTaskExecutor: Int] = [:]
10 | d[a] = 1
| |- error: conformance of 'UnownedTaskExecutor' to 'Hashable' is only available in macOS 27.0 or newer
| `- note: add 'if #available' version check
11 | return a == b
12 | }
[exit 1]
각각 아래처럼 읽는다.
- macOS 14 이하에서는 선호 API 호출이 막힌다.
Task(executorPreference:)(init(name:executorPreference:priority:operation:)),withTaskExecutorPreference가 15.0 이상이고,UnownedTaskExecutor를 타입으로 쓰는 곳도 막힌다.Equatable도 15.0 부터다(11:12). TaskExecutor는 채택 자체는 통과하지만 타입 이름으로 쓰는 곳이 막힌다.Conf14.swift는final class QE: TaskExecutor를 선언하고func h() -> any TaskExecutor { QE() }를 쓴다.-target arm64-apple-macos14에서 클래스 선언에는 진단이 없고any TaskExecutor를 쓴 4 번 줄에error: 'TaskExecutor' is only available in macOS 15.0 or newer가 하나 나온다.- 15 와 26 사이에서 막히는 것은
Hashable하나다.Equatable은 15.0 부터 쓸 수 있다. - 에러 줄이
9:7에서도 나오는 이유는var d: [UnownedTaskExecutor: Int]의 딕셔너리 키 위치다. 키 타입이Hashable이어야 하는 자리마다 걸린다.
Hashable 만 27.0 인 데에는 이유가 있다. 스레드 절에서 보겠지만 conformance 는 back-deploy 가 안 되기 때문이다. 그 자리를 채우는 방법은 아래에서 HashOld.swift 로 보인다.
UnownedTaskExecutor 의 Hashable
여기서부터가 SE-0523 이다. 현재 task 의 선호를 읽을 수 있게 되었으니(unownedTaskExecutor), 그 값으로 무언가를 찾는 쓰임이 자연스럽게 생긴다. 저자 Fabian Fett 이 pitch 에서 든 예가 executor 마다 connection 을 따로 두는 connection pool 이다. 선호가 loop A 인 task 는 loop A 에서 만든 연결을 받아야 하는데, Hashable 이 없으면 풀이 갖고 있는 executor 목록을 선형으로 훑어 같은 것을 찾아야 한다. [UnownedTaskExecutor: Connection] 딕셔너리로 한 번에 찾는 것이 목적이다.
Pool.swift 는 두 개의 Loop executor 를 가진 풀이다. lease() 는 현재 task 의 선호를 키로 idle 목록에서 연결을 꺼내고, 없으면 새로 만든다.
Pool.swift
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
final class Loop: TaskExecutor {
let name: String
let q: DispatchQueue
init(_ n: String) { name = n; q = DispatchQueue(label: n) }
func enqueue(_ job: consuming ExecutorJob) {
let j = UnownedJob(job)
q.async { j.runSynchronously(on: self.asUnownedTaskExecutor()) }
}
}
struct Connection: Sendable { let id: Int; let loop: String }
final class ConnectionPool: Sendable {
let loops: [Loop]
let state = Mutex<(next: Int, idle: [UnownedTaskExecutor: [Connection]])>((0, [:]))
init(_ loops: [Loop]) { self.loops = loops }
func lease() -> Connection {
let key = withUnsafeCurrentTask { $0?.unownedTaskExecutor }
let loopName = key.flatMap { k in loops.first { $0.asUnownedTaskExecutor() == k }?.name } ?? "any"
return state.withLock { s in
if let k = key, var list = s.idle[k], !list.isEmpty {
let c = list.removeLast(); s.idle[k] = list; return c
}
s.next += 1
return Connection(id: s.next, loop: loopName)
}
}
func release(_ c: Connection) {
guard let key = withUnsafeCurrentTask(body: { $0?.unownedTaskExecutor }) else { return }
state.withLock { $0.idle[key, default: []].append(c) }
}
func idleCount() -> [String: Int] {
state.withLock { s in
var r: [String: Int] = [:]
for (k, v) in s.idle { r[loops.first { $0.asUnownedTaskExecutor() == k }!.name] = v.count }
return r
}
}
}
@main struct M {
static func main() async {
let a = Loop("loop-A"), b = Loop("loop-B")
let pool = ConnectionPool([a, b])
for loop in [a, b, a] {
await Task(executorPreference: loop) {
let c = pool.lease()
print("\(loop.name) leased id=\(c.id) made-on=\(c.loop)")
pool.release(c)
}.value
}
print("idle:", pool.idleCount().sorted { $0.key < $1.key })
let c = pool.lease()
print("no preference leased id=\(c.id) made-on=\(c.loop)")
}
}
1
2
3
4
5
loop-A leased id=1 made-on=loop-A
loop-B leased id=2 made-on=loop-B
loop-A leased id=1 made-on=loop-A
idle: [(key: "loop-A", value: 1), (key: "loop-B", value: 1)]
no preference leased id=3 made-on=any
bash diag.sh Pool.swift 는 [exit 0] 이고 위 다섯 줄은 20 번 돌려도 같았다.
- loop-A 에서 처음 빌린 연결은 id=1 이다. 반납하면 loop-A 키 아래에 쌓인다.
- loop-B 는 키가 없어서 새로 id=2 를 만든다.
- loop-A 가 다시 빌리면 id=1 이 그대로 나온다. 딕셔너리에서 키로 찾았다.
- 선호가 없는 task 는 키가
nil이라 새로 만든다(id=3,made-on=any).
Mutex 로 풀 상태 지키기
Mutex는 값을 한 번에 한 쪽만 만지게 잠그는 타입이다. 풀을 여러 task 가 동시에 부르므로 idle 딕셔너리를 이것으로 감쌌다. 이 글에서는 Hashable 의 효과를 보려는 것이라 동기화는 단순하게 갔다.
포인터 비교와 executor 의 생존
UnownedTaskExecutor 의 Equatable 은 포인터 비교다. 제안서는 이 비교가 엄밀하게 안전하지는 않다고 인정한다. executor 가 해제되고 같은 메모리 주소에 새 executor 가 할당되면 서로 같다고 나올 수 있기 때문이다. 제안서는 오래 사는 executor 에서는 실무적으로 문제가 되지 않을 것이라고 본다. 같은 이유로 선호를 읽는 API 는 any TaskExecutor 가 아니라 UnownedTaskExecutor 를 돌려주고 UnsafeCurrentTask 에만 있다. 이미 해제된 executor 를 되살려 retain 하면 위험하기 때문이다.
이 비교의 용도로 제안서는 동기 함수에서 “기대한 executor 위에서 도는가” 를 검사하는 precondition(currentTaskExecutor == eventLoop.asUnownedTaskExecutor()) 형태를 든다. 아껴서 쓰라는 단서가 붙고, 비동기 함수나 actor 의 메서드는 어노테이션이나 custom actor executor 같은 정적인 방법을 쓰라고 한다.
Hashable 이 더해지면 이 약점이 딕셔너리 키로 옮겨 온다. 해제된 executor 의 값이 키로 남아 있다가 새 executor 와 충돌할 수 있다. 앞의 Pool.swift 는 loops 배열이 Loop 를 강한 참조로 잡고 있어서 키가 가리키는 executor 가 살아 있다. 제안서도 unowned executor 를 받아 any TaskExecutor 를 돌려주는 조회 함수를 만든다면, 돌려주는 참조가 살아 있도록 캐시에서 강한 참조로 보관하라고 적는다.
이전 OS 에서의 우회
27.0 아래에서는 Hashable 이 없지만 hash(into:) 는 15.0 부터 쓸 수 있다는 점(앞의 interface 발췌의 @_alwaysEmitIntoClient)을 이용해 키 타입을 감싸면 된다. HashOld.swift 가 그 우회다.
HashOld.swift
1
2
3
4
5
6
struct Key: Hashable {
let e: UnownedTaskExecutor
func hash(into h: inout Hasher) { e.hash(into: &h) }
static func == (l: Key, r: Key) -> Bool { l.e == r.e }
}
func f(_ e: UnownedTaskExecutor) -> Int { var d: [Key: Int] = [:]; d[Key(e: e)] = 1; return d.count }
1
[exit 0]
-target arm64-apple-macos15 와 -target arm64-apple-macos26 둘 다 진단 없이 통과한다. 제안서가 “Do nothing” 으로 든 대안이 이 모양의 래퍼와 unsafeBitCast(self, to: (Int, Int).self) 를 쓰는 확장이다. 래퍼는 호출하는 쪽마다 같은 코드를 베껴야 하고, 직접 unsafeBitCast 를 쓰는 쪽은 UnownedTaskExecutor 의 내부 배치에 의존한다. 표준 라이브러리가 hash(into:) 를 @_alwaysEmitIntoClient 로 내보내 주므로 래퍼가 내부 배치를 몰라도 된다.
제안서가 남긴 앞으로의 방향
제안서는 Future directions 에 몇 가지를 남겼다. 지금의 Swift 6.4 에서 되는 것과 안 되는 것을 컴파일해서 확인했다.
global actor 를 선호로 주기
제안서는 global actor 의 shared 인스턴스를 선호로 줄 수 있게 되면 Task(executorPreference: MainActor.shared) { example = 12 } 가 가능해질 것이라고 적는다. MainPref.swift 가 이 한 줄이다.
1
2
3
4
5
6
MainPref.swift:2:47: error: argument type 'MainActor' does not conform to expected type 'TaskExecutor'
1 | @MainActor var example = 0
2 | func f() { Task(executorPreference: MainActor.shared) { example = 12 } }
| `- error: argument type 'MainActor' does not conform to expected type 'TaskExecutor'
3 |
[exit 1]
bash diag.sh MainPref.swift 의 결과다. 아직은 MainActor 가 TaskExecutor 가 아니라서 컴파일되지 않는다. 제안서가 이 형태를 바라는 이유는 효율이다. Task { @MainActor in } 은 일단 추론된 context(둘러싼 actor 나 공용 풀)에서 시작한 뒤 main actor 로 hop 하지만, executorPreference: MainActor.shared 는 바로 actor 에 enqueue 할 수 있다. 앞에서 “선호를 준 Task 는 만들 때 바로 그 executor 에 enqueue 된다” 는 제안서 문장이 이 구분의 근거다.
closure 의 정적 isolation
두 번째 방향은 선호로 준 actor 가 클로저의 isolation 까지 정하는 것이다. 제안서는 operation: @isolated(target) () async -> () 같은 형태를 그리며, 지금처럼 worker 를 클로저 파라미터로 다시 받는 소음을 없애고 공용 풀로 갔다 돌아오는 hop 도 없애자고 한다. 앞의 TaskPrefIso.swift 가 보인 “operation 에 isolation 상속이 없다” 는 한계가 이 방향이 풀려는 문제다. 이 철자는 아직 Swift 6.4 에 없다.
다른 언어의 비슷한 도구
제안서는 Prior-Art 로 Kotlin 을 든다. 앞에서 pitch 스레드가 말한 Trio 의 cancellation shield 도 같은 문제를 다른 모양으로 푼 도구라서 함께 짚는다.
Kotlin 의 coroutine context
Kotlin 의 launch 는 Swift 의 task 생성에 해당하고 coroutine context 를 받는다. 문서의 예는 부모의 context 를 쓰는 launch { }, Dispatchers.Unconfined, 기본 풀로 가는 Dispatchers.Default, 새 스레드를 받는 newSingleThreadContext("MyOwnThread") 를 나란히 둔다. 선호를 지정하는 모양이 비슷하고, 자식 coroutine 이 부모의 context 를 물려받는 것은 선호가 structured child 로 내려가는 것과 같다. 다른 점도 있다. Swift 에는 actor isolation 이 있어서 선호는 강한 isolation 의 요구를 절대 넘어서지 못한다. 앞의 Custom actor 가 그 경우다.
Trio 의 cancellation shield
pitch 에서 johannesweiss 가 Task {} 의 상속을 원한 동기는 취소 뒤 정리 코드가 돌 수 있게 하는 것이었다. 취소된 task 에서는 많은 비동기 코드가 일을 거부하므로 Task { try await runTeardown() }.value 로 새 task 에 감싸 우회하는데, 이 우회가 공용 풀로 갔다가 I/O executor 로 되돌아오는 hop 을 만든다. 그는 Trio 의 shield 가 Swift 에 없어서 생긴 해킹이라고 했다. FranzBusch 도 이 문제는 Trio 같은 uncancellable scope 로 풀자고 답했다. 이 shield 가 Swift 에서 어떻게 제안되었는지는 SE-0504 글에서 따로 다룬다.
스레드에서 오간 이야기
SE-0417 의 pitch 는 2023-11-01 부터 11-08 까지, 리뷰는 12 월 중순부터 2024-01-23 까지, SE-0523 은 2026 년 3 월부터 4 월까지 진행되었다. 시간순으로 짚는다.
pitch 첫날의 이름과 nil (2023-11-01)
wadetregaskis 는 nil 이 다소 마법 같다며 정적인 .globalConcurrentExecutor 를 쓰면 어떻겠느냐고 물었다(#2). 같은 글에서 이것이 GCD 를 다시 만드는 것은 아닌지, TaskExecutor 가 아니라 ThreadPool 이라 불러야 하는 것은 아닌지, 직접 만든 executor 로 코어 수보다 많은 스레드를 만들면 task 안에서 블로킹 코드를 쓸 수 있게 되는 것은 아닌지도 물었다. ktoso 는 nil 이 “global 을 선호” 가 아니라 “선호 없음” 이라는 점을 설명하고 더 따져 보겠다고 답했다. 제안서의 “serial executor 도 쓸 수 있다” 는 문장은 이전 버전의 흔적이고, serial executor 는 TaskExecutor 를 채택해야만 넘길 수 있으며 default actor 의 executor 는 타입으로 노출되지 않는다고 바로잡았다(#3). John_McCall 은 스레드 풀은 구체적인 제공자일 뿐 추상 개념의 이름이 될 수 없다며 TaskExecutor 라는 이름에 의문을 보였다(#4). 앞의 Serial.swift 에러가 ktoso 의 답과 같은 결과다.
Task {} 가 왜 상속하지 않는가 (2023-11-02 부터 11-06)
johannesweiss 는 SwiftNIO 가 global executor 를 바꿔야 했던 사정을 말하면서(#10) Task {} 가 선호를 물려받는 길도 요청했다. 기본값을 바꾸자는 것이 아니라 Task(inheritTaskExecutorPreference: Bool = false) 나 Task(on: Task.currentExecutorPreference) 같은 선택 가능한 API 였다. 동기는 취소된 task 에서 정리 코드를 돌리려고 쓰는 try await Task { try await runTeardown() }.value 해킹이었다. 기본값이 왜 상속이 아니냐고 물은 것은 sliemeobn 이다(#17). task-local 과 actor context 가 Task {} 에 상속되는데 executor 선호만 지워지는 것이 의외라는 것이었다. Joe_Groff 는 별개로 SE-0338 이 nonisolated 비동기 코드를 actor 밖으로 항상 내보내게 한 것이 일반 actor 에는 과했을 수 있다고 짚었다(#11). MainActor 에는 꼭 필요한 동작이지만 다른 actor 는 같은 executor 에 남아도 되지 않겠느냐는 것이다.
ktoso 는 선을 이렇게 그었다. structured concurrency 는 실행 context 를 상속하고, unstructured 는 하지 않는다(#21, 11-06). Task {} 가 actor 의 context 를 상속하는 것은 특수한 경우이고, 일반화하려면 (on: actor) 처럼 명시하는 쪽이 맞다는 것이다. John_McCall 은 반대하기보다 구분을 설명했다. isolation 의 상속은 호출한 곳의 정적인 isolation 에 따르지만 task executor 는 본래 동적이다(#22). 앞의 11 번과 12 번이 이 선이고, TaskPrefIso.swift 의 에러가 정적 쪽의 모양이다.
선호를 읽는 API (2023-11-07 부터 11-08)
fabianfett 는 executor 를 의식하는 connection pool 을 만들려면 task 가 선호하는 executor 에 접근할 수 있어야 한다고 요청했다(#23, 11-07). 이 요청이 UnsafeCurrentTask.unownedTaskExecutor 로 이어졌고, ktoso 는 lifetime 때문에 UnsafeCurrentTask 에만 둔다고 설명했다(#28, 11-08). 앞의 Pool.swift 가 정확히 이 요청의 쓰임이다. 이 요청의 후속이 아래에서 다루는 SE-0523 이다.
Karl 은 formal isolation 이 정확성을 위한 것이고 이 제안의 executor 제어는 성능만을 위한 것이 아니냐고 물었고 assumeIsolated 와의 관계도 물었다(#24). John_McCall 은 그것이 핵심 생각이라고 답했다. executor 는 실행 자원의 추상적 제공자이고 actor 는 isolation 의 추상적 제공자라서, default actor 는 executor 를 바꾸지 않고도 isolation 을 만들 수 있으니 선호가 있어도 그 동작이 유지되길 바란다는 것이다(#25, 11-07). 문제는 actor A 의 serial executor 를 task 의 선호로 쓰는 경우다. 선택지가 셋이다. A 가 isolated 임을 인정하되 한 번에 한 actor 만 허용해서 B 로 오갈 때마다 suspend 하고 다시 enqueue 하는 것, 여러 actor 가 동시에 isolated 인 것을 허용하는 것, 그렇게 쓰지 말라고 세게 알리고 런타임은 그 상태를 무시하는 것이다. 그는 세 번째로 기울어 있다고 썼다. 앞의 OnBoth 가 이 문제가 놓인 자리다.
FranzBusch 는 unstructured task 가 선호를 상속하면 executor 가 task 밖으로 새어 나간다고 반대했고(#30, #32, 11-08), NIO 의 EventLoop 종료가 겪던 고통을 예로 들었다. John_McCall 은 executor 가 scope 가 있는 with 연산 안에만 산다는 점을 짚었다(#34). johannesweiss 는 이 우려를 받아들여 해법을 셋 꼽았다(#33). 선호를 지켜지지 않을 수도 있는 hint 로 보는 것, 바로 await 하는 Task 에만 상속을 허용해 구조를 유지하는 것, 그리고 가장 현실적이라며 선호를 물려받으면서 취소 상태를 풀어 주는 withUncancelledTask { ... } 같은 API 다. FranzBusch 는 그 문제는 Trio 의 uncancellable scope 처럼 풀어야 하고, 당분간은 선호를 읽는 unsafe 수단이면 구조화된 것처럼 보이는 task 를 직접 구현하기에 충분하다고 답했다(#37). 앞에서 본 shield 이야기가 여기서 나왔다.
리뷰 (2023-12 중순부터)
Douglas_Gregor 가 try-out toolchain 과 함께 리뷰를 열었다(#1). ktoso 는 TCPEchoAsyncChannel benchmark 를 올렸다(#8). context switch 의 p50 이 task executor 없이는 1500 이었고 있으면 19 였다. 처리량 숫자는 한쪽이 멀티스레드에서 갑자기 싱글스레드가 되는 비교가 되어 왜곡되는데, 그것이 이 기능이 설계된 런타임 동작의 변화라고 ktoso 가 밝혔다. 이 benchmark 가 NIO 와 같은 서버에서 이 제안이 무엇을 줄이는지의 근거다.
이 시기에 두 가지 가지치기가 있었다. ktoso 는 AsyncSequence 와 actor 를 executor 로 쓰는 절이 제안서에서 빠졌다고 알렸고(#10), 이유는 actor 가 task executor 가 아니기 때문이다. 앞의 Actors.swift 에서 OnBoth 가 보인 것이 이것이다. FranzBusch 는 nil 의 뜻을 enum 으로 표현하자고 했고(#13), ktoso 는 TaskExecutorPreference 구조체를 Never 트릭과 함께 탐색했으나(#15, #17) taylorswift 와 ktoso 가 AnyObject layout 때문에 어렵다고 짚었다(#19, #22). Task(on: .preferredExecutor) 를 일부러 뺀 이유는 executor 의 lifetime 때문이라고 ktoso 가 설명했다(#17).
이름도 여러 번 흔들렸다. George 는 “Preference” 가 오해를 부르는 명사이니 “Requirement” 가 낫겠다고 했고(#20), ktoso 는 실제로 preference 가 맞다고 답했다(#21). mklbtz 는 .defaultExecutor 를 제안했다(#25). ktoso 는 “global default executor as a TaskExecutor” 라고 적었다(#26, 12-18).
리뷰 후반의 세 가지 수정 (2024-01-09 부터 01-16)
ktoso 는 main queue 를 task executor 로 제공하지 않는 이유가 @MainActor 표시가 일반적인 방법이기 때문이라고 설명했다(#28, 01-09). some TaskExecutor 와 DefaultConcurrentExecutor 타입도 제안했다(#29). Nickolas_Pohilets 는 unownedTaskExecutor 가 실제 executor 가 아니라 선호를 돌려준다고 짚었고(#30), ktoso 는 MainActor 는 custom executor 를 가지고 선호를 덮어쓰며, 확인은 nonisolated 비동기 함수에서만 된다고 답했다(#31). 앞의 5 번이 이 경우다.
Douglas_Gregor 가 구조를 바로잡았다(#32, 01-10). nil(상속) 은 “global pool 에서 돌려라” 와 다르니 (any TaskExecutor)? 를 유지하고, 더 서술적인 라벨을 쓰고, 타입이 아니라 전역 변수로 두자는 것이다. 앞으로 이 값을 바꿀 수 있게 하는 가능성도 열어 두었다. ktoso 가 동의하며 라벨을 executorPreference: 로 바꿨다(#33). Douglas_Gregor 는 접두사로 “default” 보다 “global” 이 낫다고 했고(#34), wadetregaskis 는 나중에 setter 를 더할 수 있게 getter 함수로 하자고 했으며(#35), John_McCall 은 그런 개선은 Executor 프로토콜 자체에 들어가야 한다고 답했다(#36). ktoso 는 global... 로 정했고(#37, 01-11), nil 의 의미(문서화, optional 의 전달)와 globalConcurrentExecutor 도입을 정리했다(#38, 01-16). 앞의 8 번, 10 번, 13 번, 14 번이 정확히 이 수정 이후의 모양이다.
Douglas_Gregor 는 이 세 가지 수정, 곧 일관된 optional 선호, 더 서술적인 라벨, global concurrent executor 변수 때문에 리뷰를 1 월 23 일까지 일주일 더 늘렸다(#39, 01-16). mklbtz 가 수정을 칭찬했고(#40, 01-28), Douglas_Gregor 가 수락했다(#41, 01-29). 수락 공지(#1)에는 ktoso 가 리뷰어들에게 감사를 전한 답글이 이어졌다(#2).
SE-0523 의 pitch (2026-03-04 부터 03-25)
fabianfett 가 SE-0523 pitch 를 열었다(#1, 2026-03-04). SE-0417 pitch 에서 연결 풀을 말했던 그가 이번에는 풀의 구현을 문제로 들었다. ktoso 는 “이미 Equatable 인데 Hashable 을 건너뛸 이유가 없다” 고 짧게 받았다(#2, 03-12). John_McCall 이 리뷰로 넘겼다(#3, 03-25).
SE-0523 의 리뷰 (2026-03-25 부터 04-06)
John_McCall 이 리뷰를 열었다(#1, 03-25). James_Dempsey 는 제안서에 @available(SwiftStdlib 6.0, *) 로 적혀 있는데 설명 문장은 “표준 라이브러리에 실린 버전과 같은 배포 대상” 이라고 되어 있다고 짚었다(#2, 03-26). ktoso 는 conformance 는 back-deploy 가 쉽지 않아서 올바른 답은 6.4 이고, swift-evolution 의 PR #3214 로 고쳤다고 답했다(#3, 03-26). Joseph_Heck 은 +1 을 주면서 back-porting 이 되었으면 좋겠다고 썼다(#4, 03-30). John_McCall 은 conformance 는 back-deploy 할 수 없지만 구현의 hash(into:) 는 할 수 있다고 정리했고(#5, 04-07), ktoso 가 “Sounds good, can do that!” 이라고 받았다(#6, 04-08). 앞의 Avail.swift 와 HashOld.swift 가 이 결론과 정확히 맞는다. hash(into:) 는 15.0 부터 쓰이고 Hashable 과 hashValue 는 27.0 이다.
SE-0523 의 수락 (2026-04-09)
John_McCall 은 수락 공지에서 피드백이 “very light but positive” 였고 back-deployment 에 대한 질문이 몇 개 있었다고 적었다(#1, 04-09). ktoso 가 감사를 전했다(#2, 04-10).
기대 효과
- 라이브러리가 global executor 를 갈아 끼우지 않고도 자기 스레드 위에서 task 를 돌릴 수 있다. 앞의
Prefs.swift의 2 번부터 8 번이 그 모양이다. SwiftNIO 의 NIO PR #2564 가 필요했던 일이다. - 블로킹 IO 를 공용 풀 밖으로 뺄 수 있다.
withTaskExecutorPreference로 그 범위만 다른 executor 에 맡기고, 범위가 끝나면 선호가 돌아온다(17 after withPref). 이 효과는 기본 모드 전제이고NonisolatedNonsendingByDefault에서는 클로저 안의 비동기 함수가 호출한 actor 에 남는다. - actor 를 새로 정의하지 않아도 된다. isolation 이 없는 코드가 쓰는 스레드만 바꾼다.
- executor 에 묶인 자원을 task 의 선호로 찾을 수 있다.
unownedTaskExecutor와 SE-0523 의Hashable이 합쳐져서Pool.swift가 선형 탐색 없이 연결을 고른다. - 선호가 따라가는 곳과 끊기는 곳이 규칙으로 정해져 있다. structured 로만 내려가고, actor 의 executor 가 앞선다. 앞의 그림이 그 경계다.
다른 선택지는 왜 안 됐나
global executor 를 바꾸는 방법
pitch 에서 johannesweiss 가 NIO 가 이 방법을 썼다고 했다(#10). 프로세스 전체가 바뀌므로 한 라이브러리의 사정이 다른 코드에 번진다. 이 제안서가 필요해진 이유다.
Task(executorPreference: actor)
제안서 1.3 에서 TaskExecutor 프로토콜이 도입되면서 actor 를 선호로 넘기는 형태가 빠졌다. 앞의 Actors.swift 에서 OnBoth 가 보였듯 actor 의 executor 와 task 의 선호는 서로 다른 약속이다. actor 는 상호 배제까지 약속하고 task executor 는 스레드만 공급한다.
nil 을 다른 값으로 바꾸기
wadetregaskis 가 정적 .globalConcurrentExecutor 를 제안했고(#2), FranzBusch 는 enum 을(#13), ktoso 는 TaskExecutorPreference 구조체를 탐색했다(#15, #17). 최종안은 Douglas_Gregor 의 지적(#32)을 받아 nil 은 “상속”, globalConcurrentExecutor 는 “공용 풀” 로 나누었다.
Task {} 가 선호를 상속하게 하기
johannesweiss 는 선택 가능한 상속 API 를 요청했고(#10), sliemeobn 은 기본값이 왜 상속이 아니냐고 물었다(#17). John_McCall(#22)은 isolation 의 상속은 정적이고 executor 는 동적이라고 구분했고, FranzBusch(#30, #32)는 선호가 task 밖으로 새어 나가 executor 의 수명 관리가 어려워진다고 우려했다. 이 선을 따라 structured 로만 내려가게 정해졌다.
Hashable 대신 우회를 두기
SE-0523 이 “Do nothing” 으로 든 대안이다. 앞의 HashOld.swift 처럼 래퍼 타입을 만들거나 unsafeBitCast(self, to: (Int, Int).self) 를 직접 쓰는 방법이다. 동작은 하지만 매번 같은 코드를 베껴야 하고, 내부 배치를 의존하게 된다.
아무 제어도 주지 않기
제안서는 이 기능을 아예 두지 않고 개발자가 항상 isolated 파라미터를 명시적으로 넘기게 하는 방법도 검토했다. 두 가지가 걸린다. 너무 번거롭고, 스레드 배치가 메서드의 공개 API 와 ABI 에 묶인다. 선호처럼 nonisolated 함수에만 영향을 주는 장치가 없으면 개발자가 방어적으로 API 를 여러 버전 만들게 된다. 또 isolation 은 actor 의 개념이라 serial executor 로만 isolate 할 수 있고, 범용 Executor 타입으로는 못 한다.
Swift 6 모드와 마이그레이션
소스 호환성과 ABI 모두 순수 추가라서 기존 코드는 영향을 받지 않는다. 위의 Prefs.swift, Unowned.swift, Actors.swift, Lifetime.swift, WithPrefIso.swift, WithPrefLife.swift, BlockingIO2.swift, Pool.swift 는 모두 Swift 6 모드(-swift-version 6)로 컴파일했고 진단이 없었다. 진단을 일부러 낸 것은 Serial.swift, TaskPrefIso.swift, MainPref.swift 와 배포 대상을 낮춘 Avail.swift, Conf14.swift 다.
실제로 걸리는 것은 배포 대상이다. 선호 API 는 macOS 15 이상이고, UnownedTaskExecutor 의 Hashable 은 27.0 이상이다. 앞의 Avail.swift 가 두 경계를 보였다. 15 미만을 지원하는 앱은 if #available 로 갈라야 하고, 15 이상 27 미만이면 HashOld.swift 의 Key 래퍼로 딕셔너리 키를 쓸 수 있다. 27 이상으로 올리면 래퍼를 걷어 내고 [UnownedTaskExecutor: Value] 를 그대로 쓰면 된다.
executor 를 직접 구현하는 쪽에서 바뀐 것도 있다. 새 enqueue(_ job: consuming ExecutorJob) 를 구현하고, job 을 돌릴 때는 runSynchronously(on:) 대신 runSynchronously(isolatedTo:taskExecutor:) 를 쓰면 serial executor 와 task executor 를 한 번에 알려 줄 수 있다. 앞의 Both 가 그 형태다.
정리
TaskExecutor는 task 가 돌 스레드를 공급하는 프로토콜이다.Task(executorPreference:),addTask(executorPreference:),withTaskExecutorPreference로 선호를 준다.- 선호는 structured 로만 내려간다.
async let,addTask, default actor 의 메서드,@concurrent함수는 따라가고Task {},Task.detached, MainActor, custom executor 를 가진 actor 는 따르지 않는다. nil은 상속이고,globalConcurrentExecutor는 공용 풀로 되돌리는 값이다. 선호는withTaskExecutorPreference범위가 끝나면 원래대로 돌아온다.- 선호를 받은 task 는 executor 를 자기가 끝날 때까지 retain 한다.
SerialExecutor만으로는 선호가 될 수 없고, 두 역할을 다 하려면 둘 다 채택한다. UnsafeCurrentTask.unownedTaskExecutor로 현재 선호를 읽을 수 있고, SE-0523 이 그UnownedTaskExecutor에Hashable을 더해서 executor 별 자원을 딕셔너리로 찾을 수 있다.Hashable과hashValue는 anyAppleOS 27.0,hash(into:)와Equatable은 macOS 15 부터다. 그 사이 OS 에서는hash(into:)로 감싼Key구조체로 같은 효과를 낼 수 있다.- 선호보다 isolation 이 먼저다.
main()이 MainActor 라서withTaskExecutorPreference의 클로저가 main thread 에서 시작하고,NonisolatedNonsendingByDefault에서는 nonisolated 비동기 함수도 호출한 actor 에 남는다. - 선호를 준
Task의 클로저는 호출한 쪽의 actor isolation 을 상속하지 않는다. 선호는 hint 이고 쓸 곳은 이벤트 루프나 블로킹 IO 처럼 가려서 골라야 한다.
관련 글
- [SE-0472] Starting tasks synchronously from caller context: task 를 만들 때 호출한 쪽 context 에서 바로 시작하게 하는 제안서
- [SE-0461] Run nonisolated async functions on the caller’s actor by default: nonisolated 비동기 함수가 어디서 도는지에 대한 규칙
- [SE-0420] Inheritance of actor isolation: isolation 의 상속은 정적이고 executor 의 선호는 동적이라는 John_McCall 의 구분에서 정적인 쪽
- [SE-0520] Discardable result use in Task initializers:
Task초기화 함수의 반환값 - [SE-0468] Hashable conformance for Async(Throwing)Stream.Continuation: 같은 종류의 Hashable 추가 제안서
- [SE-0504] Task Cancellation Shields: pitch 에서 johannesweiss 가 원한 취소 shield 를 다루는 제안서

