포스트

[SE-0472] Starting tasks synchronously from caller context

이 글은 Swift Evolution 제안서 원문과 포럼 리뷰 스레드를 Claude Code 로 정리한 글이다. 코드는 Xcode 27 의 Swift 6.4 컴파일러로 빌드하고, 진단 메시지와 실행 결과는 실제로 컴파일하고 실행해서 나온 것을 옮겼다.


제안서 정보


한 줄 요약

Task.immediate { ... } 가 생겼다. 만든 task 를 executor 에 올려 두고 나중에 돌리는 대신, 만드는 그 자리에서 호출자의 thread 와 executor 를 그대로 쓰며 첫 suspension 까지 바로 실행한다. 동기 함수 안에서 async 함수를 부를 수 있고, 그 호출 앞쪽의 코드가 Task {} 처럼 한참 뒤가 아니라 바로 돈다. 이 글은 그 “바로” 가 정확히 언제인지를, 호출자가 어디에 있고 closure 가 어떤 isolation 을 가지는가에 따라 나눠서 컴파일러와 실행 결과로 정리한다.


어떤 문제였나

Swift Concurrency 에서 동기 함수가 async 세계로 들어가는 문은 Task {} 하나뿐이다. 그런데 Task {} 는 task 를 만들어 executor 에 올려 놓을 뿐이고, 본문은 호출자가 executor 를 놓은 뒤 언젠가 돈다. 이 “언젠가” 가 대부분은 문제가 안 되지만, 몇몇 자리에서는 문제가 된다. 이 글은 그 자리를 세 가지로 나눠서 본다. 동기 함수에서 async 함수를 부를 수 없다는 것, Task {} 본문이 호출자 코드보다 늦게 돈다는 것, 그리고 UI 에서 한 프레임이 늦는다는 것이다.

이 글의 뼈대는 이렇다. 먼저 문제를 컴파일러 진단으로 본다. 그다음 Task.immediate 의 실행 순서, MainActor.assumeIsolated 와의 관계, closure 가 물려받는 isolation, 호출한 executor 에 따라 시작하는 자리가 어떻게 갈리는지, 함수 값을 넘길 때와 task group, task local 과 우선순위, sending 을 차례로 측정한다. 그다음 스레드를 따라가고, availability 와 마이그레이션을 본다.

앞 글들은 필요한 곳에서 짧게 짚는다.

  • SE-0431 글: @isolated(any) 함수 타입. 수락 때 이 제안의 operation 에 요구된 속성이다
  • SE-0420 글: isolated 파라미터를 받는 함수와 #isolation 기본값. 이 글의 go(with:) 실험이 이 모양이다
  • SE-0461 글: nonisolated async 함수가 호출자의 isolation 에서 도는 것. 호출자 isolation 을 물려받는 다른 장치로 뒤에서 비교한다
  • SE-0430 글: sending 파라미터. Task.immediate 의 operation 이 sending 이다
  • SE-0469 글: task 에 이름을 붙이는 name: 파라미터

동기 함수에서 막히는 async 호출

앱 코드에서 흔한 모양이다. 메인 스레드에서 불린다는 것을 아는 동기 함수가 있고, 그 안에서 @MainActor 의 async 함수를 불러야 한다. 그 함수가 async 인 데에는 이유가 있다고 하자(프로토콜 요구사항이 async 라거나, 안에서 가끔 await 를 하는 식이다).

1
2
3
4
5
6
7
8
9
10
11
12
// 동기 함수에서 async 함수를 부르고 싶다
@MainActor var thingsHappened = 0

@MainActor func asyncUpdateThingsHappenedCounter() async {
  thingsHappened += 1
}

func synchronousFunction() {
  MainActor.assumeIsolated {
    await asyncUpdateThingsHappenedCounter()
  }
}

호출자가 main actor 인 것을 안다면 MainActor.assumeIsolated 로 “여기는 main actor 다” 를 컴파일러에게 알려 주면 될 것 같다. 컴파일해 보면 이렇다.

1
bash diag.sh Motivation.swift
1
2
3
4
5
6
7
8
9
10
Motivation.swift:9:28: error: cannot pass function of type '() async -> ()' to parameter expecting synchronous function type
 7 | 
 8 | func synchronousFunction() {
 9 |   MainActor.assumeIsolated {
   |                            `- error: cannot pass function of type '() async -> ()' to parameter expecting synchronous function type
10 |     await asyncUpdateThingsHappenedCounter()
   |     `- note: 'async' inferred from asynchronous operation used here
11 |   }
12 | }
[exit 1]

diag.sh 는 -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 으로 컴파일하는 한 줄짜리 스크립트다. 진단은 assumeIsolated 의 closure 가 동기 함수 타입을 받는데 await 가 들어 있어서 closure 가 async 로 추론됐다는 것이다. Swift 5, Swift 5 complete, Swift 6 모드 셋 다 같은 오류가 난다. 이 오류는 언어 모드에 달린 것이 아니다.

MainActor.assumeIsolated로 main actor 임을 단언하기

MainActor.assumeIsolated(_:file:line:) 는 지금 main actor 위에 있다고 단언하고, 그렇다면 closure 를 main actor isolated 로 실행하는 함수다. 동기 closure 만 받는다. 정말 main actor 위가 아니면 프로세스가 멈춘다(뒤의 실험에서 본다). 이 함수는 isolation 정보를 “복구” 해 줄 뿐 async 컨텍스트를 만들어 주지 않는다. 그래서 위 코드에서 await 가 들어가는 순간 오류가 난다.


호출자 뒤로 밀리는 Task 본문

그러면 Task {} 를 쓰면 된다. Task {} 안에서는 await 를 쓸 수 있다. 값은 치른다. 본문은 호출자가 main actor 를 놓은 뒤에 돈다.

제안서의 Motivation 은 이 비용을 “UI 나 성능에 민감한 자리에서 스케줄링 지연이 문제가 된다” 고 적는다. 지연의 크기가 아니라 순서가 문제인 경우도 있다. 포럼의 pitch 스레드에서 OneSadCookie 는 completion handler 기반 코드를 async 로 옮기다 겪은 일을 이렇게 말한다(pitch #6). 원래 코드는 doSomeSetup() 을 동기로 부르고 그 뒤에 doSomethingThatReliesOnSetup() 을 불러서 순서가 보장됐는데, Task {} 로 옮기면 그 보장이 없어진다. 같은 pitch 스레드에서 stephencelis 는 async 코드를 테스트할 때 “일이 시작되기” 를 기다리려고 Task.yield 와 sleep 을 끼워 넣게 된다고 말한다(pitch #7).

Order.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
// Task {} 와 Task.immediate {} 의 실행 순서
import Foundation

@MainActor var counterUsual = 0
@MainActor var counterImmediate = 0

// CLI 의 async main 은 첫 suspension 뒤 main queue 를 main thread 가 아닌 곳에서 돌릴 수 있다.
// 그래서 thread 가 아니라 main queue 위에 있는지로 판정한다
let mainKey = DispatchSpecificKey<Bool>()
func where_() -> String { DispatchQueue.getSpecific(key: mainKey) == true ? "main" : "background" }

@MainActor func sayHelloOnMain() {
  print("1 before")
  Task { @MainActor in
    counterUsual += 1
    print("5 Task {} body, counterUsual = \(counterUsual)")
  }
  print("2 after Task {}, counterUsual = \(counterUsual)")
  Task.immediate { @MainActor in
    counterImmediate += 1
    print("3 immediate sync part on \(where_()), counterImmediate = \(counterImmediate)")
    await Task.yield()
    print("6 immediate after yield on \(where_())")
  }
  print("4 after Task.immediate, counterImmediate = \(counterImmediate)")
}

@main
struct Main {
  static func main() async {
    DispatchQueue.main.setSpecific(key: mainKey, value: true)
    sayHelloOnMain()
    try? await Task.sleep(for: .milliseconds(200))
  }
}
1
2
xcrun swiftc -parse-as-library -swift-version 6 Order.swift -o x
./x
1
2
3
4
5
6
1 before
2 after Task {}, counterUsual = 0
3 immediate sync part on main, counterImmediate = 1
4 after Task.immediate, counterImmediate = 1
5 Task {} body, counterUsual = 1
6 immediate after yield on main

두 번 돌려도 같은 순서다. 읽는 법은 이렇다. 2 번 줄에서 counterUsual 이 0 이다. Task {} 를 만들었지만 호출자(sayHelloOnMain)가 main actor 를 놓지 않았으니 본문이 돌 수 없었다. 반면 3 번 줄은 Task.immediate 가 반환하기도 전에, 4 번 줄보다 먼저 찍혔고, 4 번 줄에서 counterImmediate 는 이미 1 이다. 5 번 줄(Task {} 본문)은 sayHelloOnMain 이 끝나 main actor 가 풀린 뒤에 돈다.

판정을 Thread.isMainThread 가 아니라 main queue 의 specific key 로 한 데에는 이유가 있다. CLI 프로그램의 static func main() async 는 첫 suspension 뒤에 main queue 를 main thread 가 아닌 thread 에서 돌릴 수 있어서, thread 로 판정하면 “main actor 에서 돌았나” 를 잘못 읽는다. 이 글의 where_() 와 here() 는 모두 main queue 에 건 키가 보이는지로 판정한다.

DispatchSpecificKey로 main queue 위인지 판정하기

DispatchSpecificKey 는 dispatch queue 에 값을 걸어 두기 위한 키 타입이다. 여기서는 세 단계로 쓴다.

  1. DispatchSpecificKey<Bool>() 로 키를 만든다
  2. main 에서 DispatchQueue.main.setSpecific(key:value:) 로 main queue 에 true 를 건다
  3. 지금 코드가 도는 queue 에서 DispatchQueue.getSpecific(key:) 를 부르면 main queue 위일 때만 true 가 나오고, 아니면 nil 이다

Task.yield() 와 Task.sleep(for:) 는 뒤에서 설명한다.

이 순서 차이가 Task.immediate 의 핵심이다. 그림으로 보면 이렇다.

Task {} 는 만들 때 enqueue 되어 caller 가 main actor 를 놓은 뒤에 돌고, Task.immediate 의 동기 부분은 caller 가 쥔 자리에서 바로 돌며 첫 suspension 에서 멈추면 나머지가 enqueue 된다

그림의 숫자는 위 출력의 줄 번호와 같다. 아래 칸의 점선은 Task {} 가 만들 때 enqueue 되어 5 번에서야 도는 길이고, 위 칸의 점선은 Task.immediate 가 첫 suspension 에서 멈추면 나머지(6 번)가 enqueue 되는 길이다. 3 번은 호출자가 main actor 를 쥔 채로 그대로 쓴다.


한 프레임 늦는 UI

세 번째는 UI 다. 리뷰에서 kabiroberai 가 든 예는 이런 것이다(리뷰 #25). 뷰가 나타날 때 이름을 불러오는데, API 가 캐시를 갖고 있으면 await 인데도 멈추지 않고 바로 값을 돌려준다. 이 호출을 .onAppear { Task { ... } } 로 감싸면 캐시가 있어도 ProgressView 가 잠깐 깜빡인다. 호출 앞쪽이 한 프레임 늦게 돌아서 첫 프레임에 플레이스홀더가 그려지기 때문이다. 이 현상은 뒤의 기대 효과에서 Cache.swift 로 직접 재현한다.

세 문제의 공통점은 같다. 호출자가 이미 “맞는 자리” 에 있고, 그 자리를 놓지 않은 채 async 컨텍스트로 들어가고 싶다는 것이다.


무엇이 바뀌나

제안서는 Task 에 immediate 와 immediateDetached 를, task group 에 addImmediateTask 와 addImmediateTaskUnlessCancelled 를 더한다. 이름은 새로 생겼지만 움직임은 한 문장으로 말할 수 있다. 호출한 자리가 요청한 isolation 과 같으면 만든 자리에서 바로 돌고, 다르면 지금까지처럼 enqueue 한다. 이 절은 그 문장을 풀어서 API 의 모양, “바로” 의 정확한 끝, closure 가 물려받는 isolation, 호출한 executor 에 따른 갈림, 그리고 task group 과 task local, sending 을 하나씩 측정한다.


새 API 목록

SDK 의 swiftinterface(Xcode 27, Swift 6.4)에서 옮긴 선언이다. _Concurrency.swiftmodule/arm64e-apple-macos.swiftinterface 에 있고, 접두어(_Concurrency::, Swift::)와 함수 본문은 줄였다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@available(anyAppleOS 26.0, *)
extension Task where Failure == any Error {
  @discardableResult
  @_alwaysEmitIntoClient public static func immediate(name: String? = nil, priority: TaskPriority? = nil, executorPreference taskExecutor: consuming (any TaskExecutor)? = nil, @_implicitSelfCapture @_inheritActorContext(always) operation: sending @escaping @isolated(any) () async throws -> Success) -> Task<Success, any Error>

  @discardableResult
  @_alwaysEmitIntoClient public static func immediateDetached(name: String? = nil, priority: TaskPriority? = nil, executorPreference taskExecutor: consuming (any TaskExecutor)? = nil, @_implicitSelfCapture @_inheritActorContext(always) operation: sending @escaping @isolated(any) () async throws -> Success) -> Task<Success, any Error>
}

@available(anyAppleOS 26.0, *)
extension Task where Failure == Never {
  @discardableResult
  @_alwaysEmitIntoClient public static func immediate(name: String? = nil, priority: TaskPriority? = nil, executorPreference taskExecutor: consuming (any TaskExecutor)? = nil, @_implicitSelfCapture @_inheritActorContext(always) operation: sending @escaping @isolated(any) () async -> Success) -> Task<Success, Never>
  // immediateDetached 도 같은 모양으로 한 쌍이 더 있다
}

extension TaskGroup {
  @_alwaysEmitIntoClient public mutating func addImmediateTask(name: String? = nil, priority: TaskPriority? = nil, executorPreference taskExecutor: consuming (any TaskExecutor)? = nil, @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> ChildTaskResult)

  @_alwaysEmitIntoClient public mutating func addImmediateTaskUnlessCancelled(name: String? = nil, priority: TaskPriority? = nil, executorPreference taskExecutor: consuming (any TaskExecutor)? = nil, @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> ChildTaskResult) -> Bool
}

ThrowingTaskGroup, DiscardingTaskGroup, ThrowingDiscardingTaskGroup 에도 같은 쌍이 있다(throwing 판은 operation 이 async throws). 눈에 띄는 점은 다섯 가지다.

  • Task.immediate 는 Failure 가 any Error 인 판과 Never 인 판이 따로 있다
  • Task.immediate 와 immediateDetached 의 operation 에 @_inheritActorContext(always) 가 붙어 있다
  • task group 판은 (always) 가 없는 @_inheritActorContext 다
  • operation 은 sending 이고 @isolated(any) 다. @isolated(any) 는 수락 때 요구된 사항이고, 구현 PR #81572 가 넣었다
  • executorPreference 는 consuming 이다

startSynchronously 는 pitch 때 이름이었고 SDK 에는 없다.

Task.immediate 와 addImmediateTask 의 파라미터

Task.immediate(name:priority:executorPreference:operation:) 는 task 를 만들어 바로 첫 suspension 까지 돌리는 함수다. 돌려주는 Task 는 await t.value 로 결과를 기다리거나 cancel() 로 취소할 때 쓰고, @discardableResult 라서 버려도 경고가 없다.

파라미터하는 일
nametask 이름. SE-0469 에서 들어온 파라미터다
priority우선순위. 생략하면 호출자의 우선순위를 물려받는다
executorPreference첫 suspension 뒤에 선호할 executor
operation돌릴 closure. sending, @isolated(any) 이고 호출자의 isolation 을 물려받는다

이 표의 파라미터 구성은 Task.init 과 같다. immediateDetached 와 task group 판도 같다. task group 의 addImmediateTask 는 child task 를 group 에 더하는 addTask 의 immediate 판이다. addImmediateTaskUnlessCancelled 는 addTaskUnlessCancelled 처럼 이미 취소된 group 이면 더하지 않고 false 를 돌려준다.


suspension 이란?

이 제안에서 가장 자주 나오는 말이 suspension 이다. “첫 suspension 까지 바로 돈다” 는 말이 정확하려면 이 말부터 정해야 한다. 포럼에서도 같은 질문이 나왔다. FranzBusch 가 suspension 의 정의가 필요하다고 물었고(두 번째 리뷰 #2), 저자는 이렇게 답했다. suspension 은 task 가 carrier thread 를 내주는 순간이다(두 번째 리뷰 #4, ktoso).

await 가 적힌 자리는 “potential suspension point” 다. 거기서 정말 멈출지는 실행해 봐야 안다. 호출한 함수가 값을 바로 돌려주면 멈추지 않는다. 이 글의 Cache.swift 에서 캐시에 있는 image(1) 이 그렇다. 첫 suspension 은 그래서 코드의 한 줄이 아니라 실행 중에 정해지는 순간이다. 이 구분이 뒤의 모든 측정을 읽는 열쇠다.

비유하자면 줄을 서 있는 가게 점원이다. 점원(thread)이 손님(task)의 일을 보다가 “재고 확인 중이니 기다려 주세요” 라고 하면 그 손님은 옆으로 비켜서고(suspension) 점원은 다른 손님을 받는다. Task {} 는 손님이 번호표만 받아 두고 순서를 기다리는 것이고, Task.immediate 는 손님이 바로 점원 앞에서 시작하는 것이다. 다만 점원이 이미 그 손님을 받을 수 있는 자리(같은 isolation)에 있을 때만 그렇다.


실행 순서

Task.immediate 의 첫 측정은 이 글 앞에서 이미 했다. Order.swift 의 출력(3 immediate sync part on main 이 4 after Task.immediate 보다 앞)이 그것이다. 이 출력에서 얻는 사실은 둘이다.

  1. Task.immediate 의 본문은 반환하기 전에 돈다. Task {} 본문은 호출자가 끝난 뒤에 돈다
  2. immediate 도 첫 suspension(Task.yield()) 뒤에는 보통 task 처럼 enqueue 되어 돈다. 6 번 줄은 5 번 줄보다 뒤에 찍혔다

2 번이 중요하다. Task.immediate 는 “task 전체를 동기로 돌린다” 가 아니다. 앞부분만 동기이고, 첫 suspension 을 지나면 이후는 Task {} 와 같은 규칙으로 움직인다. kabiroberai 가 pitch 에서 “synchronously” 라는 이름이 task 전체가 호출자를 막는다는 오해를 준다고 지적한 것이 이 부분이다(pitch #8).


MainActor.assumeIsolated 와의 관계

앞의 Motivation.swift 는 assumeIsolated 로는 동기 함수에서 async 함수를 못 부른다는 것을 보였다. Task.immediate 로 바꾼 MotivationOK.swift 를 보자.

1
2
3
4
5
6
7
8
9
10
11
@MainActor var thingsHappened = 0

@MainActor func asyncUpdateThingsHappenedCounter() async {
  thingsHappened += 1
}

func synchronousFunction() {
  Task.immediate {
    await asyncUpdateThingsHappenedCounter()
  }
}
1
bash diag.sh MotivationOK.swift
1
[exit 0]

경고도 오류도 없다. 그런데 이 코드의 synchronousFunction 은 isolation 이 없는 동기 함수라서 closure 도 isolation 이 없다. 그 안에서 await asyncUpdateThingsHappenedCounter() 는 @MainActor 함수를 부르므로 main actor 로 hop 해야 한다. 컴파일러는 이것을 허락한다. Task.immediate 의 closure 는 async 라서 await 가 들어갈 수 있기 때문이다.

그러면 두 도구는 어떻게 다른가. Compose.swift 가 둘을 겹쳐 쓰고, main queue 가 아닌 곳에서 부를 때의 차이를 함께 본다.

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
// assumeIsolated 와 Task.immediate 를 겹쳐 쓴다
import Foundation

@MainActor var num = 0
@MainActor func asyncMainActorMethod() async { num += 10 }

let mainKey = DispatchSpecificKey<Bool>()
func here() -> String { DispatchQueue.getSpecific(key: mainKey) == true ? "main" : "background" }

func alwaysCalledFromMainActor() {
  MainActor.assumeIsolated {
    assert(num == 0)
    Task.immediate {
      num += 1
      print("sync part: num = \(num) on \(here())")
      await asyncMainActorMethod()
      print("after await: num = \(num) on \(here())")
    }
    print("assumeIsolated body ends: num = \(num)")
  }
}

// main 이 아닌 곳에서 부르면 assumeIsolated 는 멈추고, Task.immediate 는 enqueue 한다
func viaAssume() {
  MainActor.assumeIsolated { print("assumeIsolated body") }
}

func viaImmediate() {
  Task.immediate { @MainActor in print("immediate body on \(here())") }
  print("viaImmediate returns")
}

@main
struct Main {
  static func main() async {
    setvbuf(stdout, nil, _IONBF, 0)
    DispatchQueue.main.setSpecific(key: mainKey, value: true)
    await MainActor.run { alwaysCalledFromMainActor() }
    try? await Task.sleep(for: .milliseconds(100))
    if CommandLine.arguments.count > 1 {
      await Task.detached { viaImmediate() }.value
      try? await Task.sleep(for: .milliseconds(100))
      await Task.detached { viaAssume() }.value
    }
  }
}
1
2
xcrun swiftc -parse-as-library -swift-version 6 Compose.swift -o x
./x
1
2
3
sync part: num = 1 on main
after await: num = 11 on main
assumeIsolated body ends: num = 11

assumeIsolated 안에서 Task.immediate 를 부르면 closure 는 main actor isolated 이고, 그래서 num += 1 이 바로 돈다. 출력의 순서가 그것을 보여 준다. 첫 줄 num = 1 이 먼저, 그다음 await asyncMainActorMethod() 가 같은 main actor 의 함수라서 멈추지 않고 바로 num = 11 까지 가고, 그 뒤에야 assumeIsolated body ends 가 찍힌다. 즉 이 경우 Task.immediate 의 본문 전체가 호출자(assumeIsolated 의 body)가 끝나기 전에 돌았다. 호출 안쪽에서 같은 actor 의 async 함수를 부르는 await 는 실제로 suspend 하지 않았기 때문이다.

assumeIsolated 안에서 Task.immediate 를 쓰면 async 컨텍스트가 열리고 본문이 main actor 에서 바로 돈다.

인자를 주고 main queue 밖에서 부르기

같은 파일을 인자 하나를 주고 돌리면 Task.detached 안에서 두 함수를 부른다.

1
2
./x go
echo "[exit $?]"
1
2
3
4
5
6
sync part: num = 1 on main
after await: num = 11 on main
assumeIsolated body ends: num = 11
viaImmediate returns
immediate body on main
[exit 133]

viaImmediate 는 main queue 가 아닌 곳에서 불렸고, @MainActor closure 라서 enqueue 되었다. 그래서 viaImmediate returns 가 먼저 찍히고 immediate body on main 이 뒤에 찍혔다. 그다음 viaAssume 은 같은 자리에서 assumeIsolated 를 불러 프로세스가 종료 코드 133(SIGTRAP)으로 멈췄다. 표준 오류에는 아무 문구도 나오지 않았다. setvbuf(stdout, nil, _IONBF, 0) 를 넣은 이유가 이것이다. stdout 의 버퍼링을 끄지 않으면 멈추기 전의 출력이 사라진다.

정리하면 둘은 “isolation 이 틀렸을 때” 가 다르다.

도구main actor 가 맞을 때main actor 가 아닐 때
MainActor.assumeIsolatedclosure 를 바로 실행프로세스가 멈춘다
Task.immediate { @MainActor in }바로 실행enqueue 해서 나중에 실행

assumeIsolated 는 “여기가 main actor 라고 내가 보증한다” 이고, Task.immediate 는 “맞으면 바로, 아니면 안전하게 나중에” 다. 앞의 것은 틀리면 죽고, 뒤의 것은 틀려도 안전한 대신 timing 이 달라진다.


closure 의 isolation 추론

Task.immediate 의 closure 가 어떤 isolation 을 받는지가 이 API 의 정확한 의미를 정한다. Inference.swift 는 같은 자리에 Task 와 Task.immediate 를 나란히 놓고 컴파일러가 각 closure 에 붙인 isolation 을 본다.

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
// 클로저가 어떤 isolation 을 물려받는가
@MainActor func onMain() {
  Task { print("Task") }
  Task.immediate { print("immediate") }
}

actor Caplin {
  var anything = 0
  func act() {
    Task { print("Task no capture") }
    Task { _ = self.anything }
    Task.immediate { print("immediate no capture") }
    Task.immediateDetached { print("immediateDetached") }
  }
  func group() async {
    await withDiscardingTaskGroup { group in
      group.addTask { print("addTask") }
      group.addImmediateTask { print("addImmediateTask") }
    }
  }
}

func go(with caplin: isolated Caplin) {
  Task { print("Task isolated param") }
  Task.immediate { print("immediate isolated param") }
}

func notIsolated() {
  Task { print("Task nonisolated") }
  Task.immediate { print("immediate nonisolated") }
}
1
bash isolation.sh Inference.swift

isolation.sh 는 -emit-silgen 으로 SIL 을 뽑아 함수마다 붙은 Isolation: 주석을 한 줄로 모은다. 출력에서 이 글에 필요한 closure 만 추렸다.

선언코드isolation
closure #1 in onMain()Task { }global_actor MainActor
closure #2 in onMain()Task.immediate { }global_actor MainActor
closure #1 in Caplin.act()Task { }, self 를 쓰지 않음@concurrent
closure #2 in Caplin.act()Task { }, self 를 씀actor_instance self
closure #3 in Caplin.act()Task.immediate { }, self 를 쓰지 않음actor_instance self
closure #4 in Caplin.act()Task.immediateDetached { }actor_instance self
closure #1 in Caplin.group()group body, self 를 쓰지 않음@concurrent
closure #1 in closure #1 in Caplin.group()addTask { }@concurrent
closure #2 in closure #1 in Caplin.group()addImmediateTask { }@concurrent
closure #1 in go(with:)Task { }@concurrent
closure #2 in go(with:)Task.immediate { }actor_instance caplin
closure #1, #2 in notIsolated()Task { }, Task.immediate { }@concurrent

세 줄이 핵심이다.

  1. Caplin.act() 의 Task {} 는 self 를 쓰지 않으면 @concurrent 다. actor 의 isolation 을 물려받지 않는다는 뜻이다. Task.immediate {} 는 self 를 쓰지 않아도 actor isolated 다. @_inheritActorContext(always) 가 하는 일이 이것이다. 첫 리뷰에서 John_McCall 이 이 점을 짚었다. @_inheritActorContext 는 self 를 capture 하지 않으면 non-global actor 의 isolation 을 물려주지 않으니 강제해야 한다는 것이다(리뷰 #61, John_McCall)
  2. isolated 파라미터(go(with:) 의 isolated Caplin)를 Task {} 는 물려받지 않는데 Task.immediate {} 는 물려받는다
  3. immediateDetached 의 closure 도 actor isolated 다. “detached” 는 task local 과 우선순위를 가져오지 않는다는 뜻이고 isolation 은 따로 정해진다. 6.4 SDK 에서는 (always) 가 붙어 있다

6.4 에서 immediateDetached 의 closure #4 는 actor isolated 로 추론된다. actor 안의 addImmediateTask closure 는 @concurrent 이고, main actor 함수 안의 group 에서는 addImmediateTask closure 가 MainActor, addTask closure 가 @concurrent 다.

main actor 쪽은 Dynamic.swift 의 groupOnMain() 을 같은 방식으로 isolation.sh 에 넣어 읽은 값이다. actor 쪽을 더 쪼개려고 GroupIso.swift 에서 self 를 쓰는 자리를 바꿔 보았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// actor 안 group body 가 self 를 쓰면 addImmediateTask closure isolation 이 바뀌는가
actor Caplin {
  var anything = 0
  func groupNoSelf() async {
    await withDiscardingTaskGroup { group in
      group.addImmediateTask { print("a") }
    }
  }
  func groupBodyUsesSelf() async {
    await withDiscardingTaskGroup { group in
      _ = self.anything
      group.addImmediateTask { print("b") }
    }
  }
  func groupChildUsesSelf() async {
    await withDiscardingTaskGroup { group in
      group.addImmediateTask { _ = self.anything }
    }
  }
}
1
2
3
4
5
6
closure #1 in Caplin.groupNoSelf()                    @concurrent
closure #1 in closure #1 in Caplin.groupNoSelf()      @concurrent
closure #1 in Caplin.groupBodyUsesSelf()              actor_instance self
closure #1 in closure #1 in Caplin.groupBodyUsesSelf() @concurrent
closure #1 in Caplin.groupChildUsesSelf()             actor_instance self
closure #1 in closure #1 in Caplin.groupChildUsesSelf() actor_instance self

body 가 self 를 쓰지 않으면 group body 와 child 가 모두 @concurrent 이고, body 가 self 를 쓰면 body 는 actor isolated 이고 child 는 @concurrent 이며, child 가 self 를 쓰면 child 가 actor isolated 다. actor 의 isolation 은 closure 가 self 를 쓰는 자리에서만 이어진다. 위 표의 Caplin.group() 안 closure #1(group body)도 @concurrent 였다.

isolation.sh 로 closure 의 isolation 읽기

swiftc 의 -emit-silgen 은 SIL 을 최적화 없이 뽑는 옵션이다. SIL 의 함수 선언 위에는 // Isolation: ... 주석이 붙는다. isolation.sh 는 awk 로 이 주석과 함수 이름을 짝지어 한 줄씩 보여 준다. 컴파일러 내부 구현에 기대는 방법이라 버전마다 모양이 달라질 수 있다. 이 글의 표는 Swift 6.4 의 출력이다.


호출한 executor 에 따라 갈리는 시작

“맞으면 바로, 아니면 enqueue” 가 어떤 모양으로 보이는지가 이 제안의 핵심이다. 컴파일러는 sayHello 가 어디서 불릴지 모르기 때문에 이 판정을 실행 시점에 한다. Dynamic.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
// Dynamic.swift 일부. 전체는 samples 에 있다
// 동기 함수. 컴파일러는 이 함수가 어디서 불리는지 모른다
func sayHello(_ from: String) {
  Task { @MainActor in counterUsual += 1 }
  let tag = from
  Task.immediate { @MainActor in
    counterImmediate += 1
    print("[\(tag)] immediate body runs")
  }
  print("[\(from)] sayHello returns")
  // 여기서 값을 읽으려면 main 이어야 하므로 MainActor 로 hop 해서 찍는다
  let label = from
  Task { @MainActor in
    print("[\(label)] seen later: usual=\(counterUsual) immediate=\(counterImmediate)")
  }
}

@MainActor func sayHelloOnMain() {
  counterUsual = 0; counterImmediate = 0
  sayHello("main")
  print("[main] right after sayHello: usual=\(counterUsual) immediate=\(counterImmediate)")
}

actor Caplin {
  var anything = 0
  func sayHelloFromCaplin() {
    sayHello("caplin")
  }
  func act() {
    Task.immediate {
      self.anything += 1
      print("[caplin] immediate sync part, anything=\(self.anything)")
    }
    Task.immediateDetached {
      self.anything += 1
      print("[caplin] immediateDetached sync part, anything=\(self.anything)")
    }
    print("[caplin] after both, anything=\(anything)")
  }
}

// 아무 isolation 도 없는 immediate 는 부른 스레드에서 시작한다
func fromBackground() {
  let caller = pthread_mach_thread_np(pthread_self())
  Task.immediate {
    let start = pthread_mach_thread_np(pthread_self())
    print("[nonisolated] same thread at start: \(start == caller)")
    try? await Task.sleep(for: .milliseconds(10))
    print("[nonisolated] resumed on same thread: \(pthread_mach_thread_np(pthread_self()) == caller)")
  }
  print("[nonisolated] caller continues")
}
1
2
xcrun swiftc -parse-as-library -swift-version 6 Dynamic.swift -o x
./x
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[main] immediate body runs
[main] sayHello returns
[main] right after sayHello: usual=0 immediate=1
[main] seen later: usual=1 immediate=1
[caplin] sayHello returns
[caplin] immediate body runs
[caplin] seen later: usual=1 immediate=1
[caplin] immediate sync part, anything=1
[caplin] immediateDetached sync part, anything=2
[caplin] after both, anything=2
[nonisolated] same thread at start: true
[nonisolated] caller continues
[nonisolated] resumed on same thread: true
[group] addImmediateTask start on main
[group] after adding, on main
[group] addTask start on background
[group] addImmediateTask resumed on main

main actor 에서 부른 @MainActor closure 는 바로 시작하고, Caplin 에서 부른 같은 closure 는 main 으로 enqueue 되고, isolation 이 없는 호출은 호출한 thread 에서 시작한다는 세 줄 표

세 줄을 따로 읽는다.

  1. main actor 에서 부름. [main] immediate body runs 가 sayHello returns 보다 앞이고, 돌아온 직후 usual=0 immediate=1 이다. closure 가 @MainActor 이고 호출자도 main actor 라서 맞았고, 바로 돌았다. Task {} 쪽은 아직 0 이다
  2. Caplin 에서 부름. 같은 closure 가 @MainActor 인데 호출자는 Caplin 이다. 이 출력에서는 sayHello returns 가 먼저, immediate body runs 가 나중이다. 맞지 않으니 enqueue 된 것으로 읽는다. 다만 print 순서는 실행마다 바뀔 수 있어서(아래), 이 판정은 값으로 따로 확인한다
  3. isolation 이 없는 호출. 같은 thread 에서 시작했다(same thread at start: true). 호출자가 isolation 이 없고 closure 도 없으니 어디서든 맞는다

Caplin 줄 가운데 [caplin] immediate sync part, anything=1 과 immediateDetached ... anything=2 는 Task.immediate 와 immediateDetached 가 모두 actor 안에서 바로 돌고, 호출자의 act() 가 끝나기 전에 anything 이 2 가 된 것(after both, anything=2)을 보여 준다. 두 closure 는 같은 actor 를 쥔 채 순서대로 돌았다.

이 출력은 실행마다 조금씩 다르다. Dynamic 을 100번 돌리니 출력이 첫 실행과 똑같은 것은 70번이었다. [nonisolated] resumed on same thread 가 false 인 것이 28번, Caplin 의 sayHello returns 가 immediate body runs 보다 뒤로 밀린 것이 2번이었다. 시작 시점의 same thread at start 는 100번 모두 true 였다. 첫 suspension 뒤는 task 가 어느 thread 에서 이어지는지 약속하지 않으므로, 이 글에서 “같은 thread” 를 근거로 쓰는 곳은 시작 시점뿐이다.

print 순서가 뒤집히는 이상 enqueue 여부는 순서가 아니라 값으로 판정해야 한다. DynamicCheck.swift 는 Task.immediate 가 돌아온 직후에 body 가 이미 돌았는지를 Mutex 플래그로 보고, body 가 호출자와 같은 thread 에서 도는지를 thread 번호로 비교한다.

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
// sayHello 의 Task.immediate 가 인라인인지 enqueue 인지를 출력 순서가 아니라 값으로 본다
import Foundation
import Synchronization

let ran = Mutex(false)
func tid() -> UInt32 { pthread_mach_thread_np(pthread_self()) }

func sayHello(_ from: String) {
  ran.withLock { $0 = false }
  let caller = tid()
  Task.immediate { @MainActor in
    ran.withLock { $0 = true }
    print("[\(from)] body on caller thread: \(tid() == caller)")
  }
  let seen = ran.withLock { $0 }
  print("[\(from)] right after Task.immediate returns, body already ran: \(seen)")
}

@MainActor func onMain() { sayHello("main") }
actor Caplin { func call() { sayHello("caplin") } }

@main struct Main {
  static func main() async {
    setvbuf(stdout, nil, _IONBF, 0)
    onMain()
    try? await Task.sleep(for: .milliseconds(30))
    await Caplin().call()
    try? await Task.sleep(for: .milliseconds(30))
  }
}
1
2
xcrun swiftc -parse-as-library -swift-version 6 DynamicCheck.swift -o x
./x
1
2
3
4
[main] body on caller thread: true
[main] right after Task.immediate returns, body already ran: true
[caplin] right after Task.immediate returns, body already ran: false
[caplin] body on caller thread: false

200번 돌린 결과다. main actor 에서 부르면 Task.immediate 가 돌아온 시점에 body 가 이미 돌았고(200번 모두 true) body 는 호출자와 같은 thread 에서 돌았다(200번 모두 true). Caplin 에서 부르면 body 는 호출자와 다른 thread 에서 돌았다(200번 모두 false). 돌아온 시점에 body 가 아직 돌지 않았다는 값(false)은 199번이었고, 나머지 한 번은 enqueue 된 body 가 다른 thread 에서 곧바로 돌기 시작해 플래그를 읽는 시점과 겹친 것이다. 정리하면 Caplin 에서 부르면 body 가 호출자와 다른 thread 에서 도는 것이 매번 확인되었고, 이것이 enqueue 된 것이다.

group 의 마지막 네 줄은 다음 절에서 읽는다.

Mutex 와 pthread_self 로 시작 자리 판정하기

Mutex 는 Synchronization 모듈의 잠금 타입이다. withLock 클로저 안에서만 값을 읽고 쓰므로, 호출자 thread 와 body 가 도는 thread 가 같은 플래그를 동시에 만져도 안전하다. 여기서는 body 가 돌았다는 표시를 담는 용도다. pthread_self() 는 지금 코드가 도는 thread 의 핸들을 돌려주고, pthread_mach_thread_np 는 그 핸들을 mach thread 번호로 바꾼다. 두 번호가 같으면 같은 thread 다. 이 비교는 isolation 이 없는 호출에서만 의미가 있다. main actor 판정에는 쓰지 않는다. main queue 가 main thread 가 아닌 곳에서 돌 수 있기 때문이다. 그래서 here() 는 DispatchQueue.getSpecific 로 main queue 인지를 본다.


함수 값을 넘길 때

closure 가 아니라 함수를 그대로 넘기면 어떻게 될까. closure 는 호출한 자리의 isolation 을 물려받는데, 함수 값은 이미 자기 isolation 을 갖고 있다. FuncRef.swift 가 @MainActor 함수 work 를 Task.immediate(operation: work) 로 넘긴다.

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
// 클로저가 아니라 함수 값을 넘기면 isolation 은 함수가 정한다
import Foundation

let mainKey = DispatchSpecificKey<Bool>()
func here() -> String { DispatchQueue.getSpecific(key: mainKey) == true ? "main" : "background" }

@MainActor func work() async {
  print("work runs on \(here())")
}

// 아무 isolation 도 없는 동기 함수. 어디서 불릴지 모른다
func start(_ label: String) {
  Task.immediate(operation: work)
  print("[\(label)] start returns")
}

@MainActor func startOnMain() {
  start("main")
}

@main
struct Main {
  static func main() async {
    setvbuf(stdout, nil, _IONBF, 0)
    DispatchQueue.main.setSpecific(key: mainKey, value: true)
    await MainActor.run { startOnMain() }
    try? await Task.sleep(for: .milliseconds(50))
    await Task.detached { start("background") }.value
    try? await Task.sleep(for: .milliseconds(50))
  }
}
1
2
3
4
work runs on main
[main] start returns
[background] start returns
work runs on main

start 는 isolation 이 없는 동기 함수이고 work 는 @MainActor 다. 이 출력은 main 에서 불린 호출이 work 먼저, background 에서 불린 호출이 start returns 먼저다. 다만 100번 돌리면 background 호출 쪽 순서가 한 번 뒤집혔다. print 순서만으로는 판정할 수 없어서 FuncRefCheck.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
// 함수 값을 넘겼을 때 enqueue 여부를 출력 순서가 아니라 값으로 본다
import Foundation
import Synchronization

let mainKey = DispatchSpecificKey<Bool>()
func here() -> String { DispatchQueue.getSpecific(key: mainKey) == true ? "main" : "background" }
let ran = Mutex(false)

@MainActor func work() async {
  ran.withLock { $0 = true }
}

func start(_ label: String) {
  ran.withLock { $0 = false }
  Task.immediate(operation: work)
  let seen = ran.withLock { $0 }
  print("[\(label)] right after Task.immediate returns, work already ran: \(seen)")
}

@MainActor func startOnMain() {
  start("main")
}

@main
struct Main {
  static func main() async {
    setvbuf(stdout, nil, _IONBF, 0)
    DispatchQueue.main.setSpecific(key: mainKey, value: true)
    await MainActor.run { startOnMain() }
    try? await Task.sleep(for: .milliseconds(50))
    await Task.detached { start("background") }.value
    try? await Task.sleep(for: .milliseconds(50))
  }
}
1
2
[main] right after Task.immediate returns, work already ran: true
[background] right after Task.immediate returns, work already ran: false

200번 돌린 결과 main 호출은 200번 모두 true, background 호출은 200번 모두 false 였다. main 에서 부르면 Task.immediate 가 돌아오기 전에 work 가 돌았고, background 에서 부르면 enqueue 되었다.

closure 의 isolation 은 start 의 isolation(없음)에서 오지만, 함수 값 work 는 @MainActor 가 스스로 정한다. 이 결과는 @isolated(any) 가 요구된 이유와 이어진다. operation 이 자기 isolation 을 값으로 들고 있어야 런타임이 “지금 호출자가 이 isolation 과 맞는가” 를 확인할 수 있다(SE-0431 글).


구조화된 child task

task group 의 addImmediateTask 가 isolation 이 없는 child closure 를 어디서 시작하는지를 Worker.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
// 제안서의 Worker 예제. nonisolated 로 추론되는 immediate child task 는 어디서 시작하는가
import Foundation

func tid() -> UInt32 { pthread_mach_thread_np(pthread_self()) }

actor Worker {
  func workIt() async {
    let caller = tid()
    await withDiscardingTaskGroup { group in
      group.addImmediateTask {
        print("[child] start on caller thread: \(tid() == caller)")
        try? await Task.sleep(for: .milliseconds(20))
        print("[child] resumed on caller thread: \(tid() == caller)")
      }
      print("[worker] after addImmediateTask")
    }
  }
}

@main
struct Main {
  static func main() async {
    await Worker().workIt()
  }
}
1
2
3
[child] start on caller thread: true
[worker] after addImmediateTask
[child] resumed on caller thread: true

100번 돌린 결과 시작 줄은 100번 모두 true 였다. 재개 줄은 34번 false 였다. 첫 suspension 뒤는 어느 thread 에서 이어질지 약속이 없다.

group body 와 child 의 isolation 은 WorkerCheck.swift 가 직접 출력한다. iso() 는 isolated 파라미터의 기본값 #isolation 으로 지금 코드가 어느 actor 위에 있는지를 문자열로 돌려준다(SE-0420 글).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Worker 의 group body 가 actor 위에서 도는지, child 시작 thread 가 body thread 와 같은지
import Foundation

func tid() -> UInt32 { pthread_mach_thread_np(pthread_self()) }
func iso(_ a: isolated (any Actor)? = #isolation) -> String { a.map { "\(type(of: $0))" } ?? "nil" }

actor Worker {
  func workIt() async {
    let caller = tid()
    print("[worker] isolation in workIt: \(iso()) main thread: \(pthread_main_np() == 1)")
    await withDiscardingTaskGroup { group in
      let bodyT = tid()
      print("[body] isolation: \(iso()) body thread == caller: \(bodyT == caller)")
      group.addImmediateTask {
        print("[child] isolation: \(iso()) start == body thread: \(tid() == bodyT)")
        try? await Task.sleep(for: .milliseconds(20))
        print("[child] resumed == body thread: \(tid() == bodyT)")
      }
    }
  }
}

@main struct Main { static func main() async { await Worker().workIt() } }
1
2
3
4
[worker] isolation in workIt: Worker main thread: false
[body] isolation: nil body thread == caller: true
[child] isolation: nil start == body thread: true
[child] resumed == body thread: true

Worker.swift 에서 group body 와 child closure 는 둘 다 isolation 이 없고, child 는 호출자 thread 에서 시작한다. 100번 돌려 start == body thread 는 100번 모두 true, resumed == body thread 는 17번 false 였다. 호출자 thread 는 pthread_main_np 기준으로 main thread 가 아닌(100번 모두) pool thread 라서, CLI 의 main thread 문제가 아니다.

앞의 Dynamic.swift 마지막 네 줄은 main actor 위에서 같은 일을 한 것이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Dynamic.swift 의 groupOnMain
@MainActor func groupOnMain() async {
  await withDiscardingTaskGroup { group in
    group.addImmediateTask {
      print("[group] addImmediateTask start on \(here())")
      try? await Task.sleep(for: .milliseconds(10))
      print("[group] addImmediateTask resumed on \(here())")
    }
    group.addTask {
      print("[group] addTask start on \(here())")
    }
    print("[group] after adding, on \(here())")
  }
}

출력은 이랬다.

1
2
3
4
[group] addImmediateTask start on main
[group] after adding, on main
[group] addTask start on background
[group] addImmediateTask resumed on main

main actor 위에서 부른 addImmediateTask 는 main 에서 시작했고 addTask 는 background 에서 시작했다. 앞 절에서 본 것처럼 이 addImmediateTask closure 는 main actor isolated 이고 addTask closure 는 @concurrent 다. 100번 돌려 addImmediateTask 가 after adding 보다 먼저 시작한 것이 100번이었다.


task local, 우선순위, 이름

Task.immediate 가 물려받는 것과 immediateDetached 가 버리는 것은 Task {} 와 Task.detached {} 의 관계와 같다. Locals.swift 가 둘을 같은 바깥 task 안에서 비교한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// immediate task 가 물려받는 것: task local, 우선순위, 이름
enum Trace { @TaskLocal static var id = "none" }

@main
struct Main {
  static func main() async {
    await Task(priority: .utility) {
      await Trace.$id.withValue("outer") {
        let t = Task.immediate(name: "fast-path") {
          print("immediate: id=\(Trace.id) priority=\(Task.currentPriority) name=\(Task.name ?? "nil")")
        }
        await t.value
        let d = Task.immediateDetached {
          print("immediateDetached: id=\(Trace.id) priority=\(Task.currentPriority)")
        }
        await d.value
      }
    }.value
  }
}
1
2
immediate: id=outer priority=TaskPriority.low name=fast-path
immediateDetached: id=none priority=TaskPriority.medium

Task.immediate 는 task local id 를 outer 로 물려받았다. immediateDetached 는 task local 을 하나도 복사하지 않아 기본값 none 이 나왔다. name: 은 SE-0469 의 파라미터이고 Task.name 으로 읽는다.

TaskLocal 로 task 에 값 붙이기

@TaskLocal 은 task 와 그 child task 에 값이 따라가는 저장소다. Trace.$id.withValue("outer") { ... } 로 범위 안의 값을 바꾼다. Task {} 와 Task.immediate {} 는 만들 때 현재 값을 복사해 가고, detached 계열은 복사하지 않는다. Task.currentPriority 는 지금 task 의 우선순위다.


sending 인 operation

operation 이 sending 이므로 closure 가 잡은 값이 호출자 쪽에서 동시에 쓰이면 컴파일러가 막는다. Sending.swift 는 일부러 data race 를 만든다.

1
2
3
4
5
6
7
8
9
10
// operation 은 sending 이다
final class Box { var n = 0 }

@MainActor func use() {
  let box = Box()
  Task.immediateDetached { @concurrent in
    box.n += 1
  }
  box.n += 1
}
1
bash diag.sh Sending.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Sending.swift:6:8: error: sending value of non-Sendable type '() async -> ()' risks causing data races [#RegionIsolation::SendingRisksDataRace]
 4 | @MainActor func use() {
 5 |   let box = Box()
 6 |   Task.immediateDetached { @concurrent in
   |        |- error: sending value of non-Sendable type '() async -> ()' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |        `- note: Passing value of non-Sendable type '() async -> ()' as a 'sending' argument to static method 'immediateDetached(name:priority:executorPreference:operation:)' risks causing races in between local and caller code
 7 |     box.n += 1
 8 |   }
 9 |   box.n += 1
   |   `- note: access can happen concurrently
10 | }
11 | 

[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>
[exit 1]

@concurrent 로 closure 를 main actor 에서 떼어내면 box 는 closure 로 넘어간 값(sending)이 되는데, 그 뒤 호출자가 box.n += 1 로 같은 값을 만진다. 컴파일러가 이것을 access can happen concurrently 로 막았다. 이 규칙은 SE-0430 의 sending 과 SE-0414 의 region 분석이 하는 일이다. Task.immediate 가 바로 돈다고 해서 이 검사가 느슨해지지는 않는다.


첫 suspension 전의 actor 상태

마지막 하나는 제안서의 Future Directions 에서 가져온 코드다. immediateDetached 로 actor 의 상태를 만지는 예제다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 제안서 Future Directions 의 예제. immediateDetached 안에서 actor 상태를 만진다
actor Caplin {
  var num: Int = 0

  func check() {
    Task.immediateDetached {
      num += 1

      try await Task.sleep(for: .seconds(1))

      num += 1
    }

    num += 1
  }
}
1
bash diag.sh Future.swift
1
2
3
4
5
6
7
8
9
10
11
Future.swift:6:10: warning: unstructured throwing task created by 'immediateDetached(name:priority:executorPreference:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
 4 | 
 5 |   func check() {
 6 |     Task.immediateDetached {
   |          |- warning: unstructured throwing task created by 'immediateDetached(name:priority:executorPreference:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
   |          `- note: to silence this warning, handle the error inside the task, or store/discard the task value explicitly
 7 |       num += 1
 8 | 

[#NoUseUnstructuredThrowingTask]: <https://docs.swift.org/compiler/documentation/diagnostics/no-use-throwing-unstructured-task>
[exit 0]

이 코드는 컴파일된다. 경고는 task 의 값을 쓰지 않아서 생긴 것이고, 눈여겨볼 곳은 closure 안의 num += 1 이다. actor 의 프로퍼티를 self. 없이 만지는데도 오류가 없다. closure 가 actor isolated 로 추론되었다는 앞의 표와 같은 이야기다. 6.4 에서 이 예제는 오류 없이 컴파일된다.


스레드에서 오간 이야기

pitch 에서 수락까지 스레드는 크게 다섯 갈래로 흘렀다. 왜 필요한가, 이름을 무엇으로 할까, 다른 isolation 의 closure 는 어떻게 할까, 순서 보장은 어디까지인가, 그리고 왜 Task {} 의 기본을 바꾸지 않는가다. 아래는 날짜 순서를 따라 그 갈래를 하나씩 정리한 것이다. 인용은 짧게 줄였고 “리뷰 #n” 은 스레드의 글 번호다.


pitch 에서 확인된 필요

2025년 2월 19일 ktoso 가 Task.startSynchronously 를 pitch 했다(pitch #1). 이름에 자신이 없다고 적고 시작했다. 같은 스레드의 사용 사례는 세 방향이었다.

  • completion handler 를 async 로 옮길 때 setup 이 동기로 끝나던 순서를 지키고 싶다(OneSadCookie, pitch #6)
  • 테스트에서 일이 시작되길 기다리느라 Task.yield 와 sleep 을 끼운다(stephencelis, pitch #7)
  • AsyncSequence 나 Combine 에서 첫 이벤트가 한 박자 늦는다(davbeck, pitch #12)

대안도 나왔다. dmt 는 executor 를 기준으로 하는 접근을 제안했는데(pitch #2), ktoso 는 그러려면 @isolated(to:) 같은 것이 필요하다고 답했다(pitch #3). kean 은 Nuke 에서 겪은 thread hop 문제를 들며 “await from sync context” 같은 방향을 물었다(pitch #15, #18). ktoso 는 왜 새 메서드여야 하는지를 따로 설명했다(pitch #16).


리뷰 초반의 필요성 논쟁

첫 리뷰는 Tony Allevato 가 열었다(리뷰 #1, allevato). mickeyl 이 스케줄링 지연이 그렇게 중요한지 의문을 달았고(리뷰 #2), ktoso 는 IPC handshake 에서 첫 메시지가 나가는 시간 같은 예를 들었다(리뷰 #3). 다른 방향의 답이 더 설득력이 있었다. John_McCall 은 이것이 스케줄러 튜닝이 아니라고 했다. 의미가 달라진다는 것이다. 호출한 actor 에 대해 atomic 하게 시작하기 때문이다(리뷰 #6, John_McCall).

구체적인 사례도 나왔다.

  • harlanhaskins: UIKit 의 dropInteraction(_:performDrop:) 가 끝나기 전에 로딩이 시작되지 않으면 UIKit 이 내용을 걷어 간다(리뷰 #7, harlanhaskins)
  • Andropov: AsyncSequence 구독 순서. Task { for await ... } 뒤에 sequence.add(...) 를 부르면 task 가 아직 구독을 시작하지 않아 이벤트를 놓칠 수 있다(리뷰 #8, #13, Andropov)

이름 짓기

가장 길게 이어진 이야기가 이름이다. 후보를 시간순으로 모으면 이렇다.

후보제안한 사람논점
startSynchronouslypitch 원안“synchronously” 가 task 전체가 호출자를 막는다는 인상을 준다(pitch #8, kabiroberai)
startImmediatelykabiroberai다른 말이 낫다(pitch #8, 리뷰 #25)
immediate, immediateDetachedpyrtsa간결하다(pitch #9, 리뷰 #50)
continue, inline, start, startOnCallerktoso후보 목록(리뷰 #34)
enqueueOnlyIfNecessaryJon_Shier반대로 부르자는 쪽(리뷰 #36)
startEagerlybrendon새치기 느낌(리뷰 #45)
inlineContext, startOnCallerjaleel(리뷰 #47)
startSynchronouslyIfAbleJumhyn정확하지만 길다(리뷰 #49)

Kotlin 의 CoroutineStart.UNDISPATCHED 가 비슷한 개념이라는 지적도 나왔다(리뷰 #53, mtsrodrigues). 리뷰가 진행되던 4월 8일에는 allevato 가 새 이름을 더 받겠다고 공지했다(리뷰 #52, allevato). 이 시점에서 Task.immediate 지지가 모이기 시작했다(sharplet, 리뷰 #48).

이름 논쟁의 밑에는 “synchronously” 가 정확히 무엇을 뜻하는가 하는 문제가 있었다. ktoso 는 potential suspension point 는 컴파일 시점의 말이고 실제 suspension 은 런타임의 일이라고 거듭 답했다(리뷰 #38, #40). 이 글의 “suspension 이란?” 절이 이 대화를 정리한 것이다.


다른 isolation 의 closure 를 허용할 것인가

초안은 closure 의 isolation 이 호출자와 같아야 한다는 제한을 두었다. 이 제한이 가장 크게 흔들렸다. ktoso 는 다른 isolation 이면 중간에 suspend 할 수 있어서 막아야 한다고 설명했다(리뷰 #9, ktoso). hborla 는 다른 isolation 으로의 전환을 “첫 dynamic suspension point” 로 보면 안전하다는 방향을 제시했다(리뷰 #32, hborla). 같은 isolation 이면 멈추지 않는다는 보장이 필요한지를 kabiroberai 가 확인했고, ktoso 는 그렇다고 답했다(리뷰 #51, #54).

리뷰는 첫 번째에서 수정 요청으로 끝났다. allevato 는 closure 가 호출자와 같은 isolation 이어야 한다는 제한을 풀고 API 이름도 다시 정하자고 했다. 동적 첫 suspension 이 어차피 예측하기 어렵다는 이유였다(수정 요청 #1, allevato). John_McCall 은 @_inheritActorContext 가 필요하다고 했다. 위의 Inference.swift 표에서 본 것처럼, 이 속성이 없으면 self 를 capture 하지 않는 closure 가 @concurrent 로 추론되어 통째로 비동기로 돌기 때문이다. 런타임이 미리 판단하지 말고 funclet 을 동기로 시작해서 executor 전환 검사가 판정하게 하자는 것이었다(수정 요청 #2, John_McCall). ktoso 는 이를 받아들여 세 경우로 정리했다(수정 요청 #3, ktoso).

  1. 정적으로 같은 isolation: 바로 실행
  2. 다른 isolation: task switch 로 enqueue
  3. 동적으로 nonisolated: 가짜 executor 로 바로 실행

이것이 이 글의 DynamicCheck.swift 가 확인한 구조다.


순서 보장은 어디까지인가

prachi 는 EventDispatcher 처럼 FIFO 가 필요한 코드를 걱정했고(리뷰 #18, prachi), ktoso 는 default actor 에도 FIFO 보장은 없다고 답했다(리뷰 #19, ktoso). John_McCall 은 custom executor 가 FIFO 일 필요도 없다고 덧붙였다(리뷰 #21, #31, John_McCall). 이 대화가 다음 기대를 잘라 낸다. Task.immediate 는 “내가 시작할 순서” 를 정해 주지만, 여러 task 가 actor 에 들어오는 순서까지 약속하지는 않는다.

CharlesS 는 이것이 actor 의 보장을 깨지 않느냐고 물었다. @syncable 같은 표시가 필요하다는 생각이었다(리뷰 #16, CharlesS). John_McCall 은 깨지 않는다고 답했다(리뷰 #17, John_McCall).

filip-sakel 은 forward progress 와 @unsafe 를 물었는데, ktoso 는 SE-0461 과 같은 균형(overhang 대 excessive switching)이라고 답했다(리뷰 #11, #12). kean 은 GCD 에 비유했고(리뷰 #22, #24), John_McCall 은 callback 기반 비동기 호출은 실질적으로 동기 시작이라고 짚었다(리뷰 #23, John_McCall).


왜 Task 의 기본을 바꾸지 않는가

sliemeobn 이 Task {} 의 기본을 이렇게 바꾸면 안 되는지 물었다(리뷰 #57, sliemeobn). John_McCall 의 답이 분명했다. 길이 없다. 의미를 깨고, re-entrancy 를 만들고, 교착을 만들 수 있다(리뷰 #60, John_McCall). hborla 도 Task.init 을 바꾸지 말자는 쪽이었다(리뷰 #65, hborla).


두 번째 리뷰와 수락

두 번째 리뷰는 5월 5일에 시작해 19일까지였다(두 번째 리뷰 #1, allevato). 이름은 Task.immediate 로 바뀐 채였다. FranzBusch 는 suspension 의 정의, @isolated(any) 가 빠졌는지, @discardableResult 를 두는지를 물었다(두 번째 리뷰 #2, FranzBusch). ktoso 의 답(두 번째 리뷰 #4)은 세 가지다. suspension 은 carrier thread 를 내주는 것이고, @isolated(any) 는 PR 81572 에서 들어왔고, @discardableResult 는 일관성을 위해 유지한다. Andropov 는 이것으로 AsyncSequence 를 관찰하는 일(SE-0475 Observations)이 믿을 만한지 물었고, ktoso 는 구현과 timing 에 달렸다고 했다. 다른 suspension point 와 같다는 것이다(두 번째 리뷰 #5, #6).

5월 21일 allevato 가 수락을 알렸다. 이름 변경과 같은 isolation 제한 제거는 두 번째 리뷰 때 이미 반영되어 있었고, 수락 때 붙은 수정은 operation 이 @isolated(any) 여야 한다는 것 하나였다(수락 #1, allevato).


기대 효과

이 API 가 쓸모 있는 자리는 “호출자가 이미 맞는 자리에 있고, 호출 앞쪽을 지금 하고 싶은” 경우다. 셋으로 나눠 본다.


캐시 적중 때 한 프레임을 아끼기

앞에서 본 UI 깜빡임을 Cache.swift 로 재현한다. 캐시에 있으면 멈추지 않는 image(_:) 를 탭 이벤트에서 부른다.

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
// 캐시에 있으면 멈추지 않는 async 함수를 UI 이벤트에서 부른다
@MainActor final class ImageModel {
  var cache: [Int: String] = [1: "cached-1"]
  var shown = "placeholder"

  func image(_ id: Int) async -> String {
    if let hit = cache[id] { return hit }          // 멈추지 않는 빠른 경로
    try? await Task.sleep(for: .milliseconds(20))  // 실제로 멈추는 느린 경로
    cache[id] = "loaded-\(id)"
    return "loaded-\(id)"
  }

  func tapWithTask(_ id: Int) {
    Task { shown = await image(id) }
    print("Task {}         id=\(id) right after tap: \(shown)")
  }

  func tapWithImmediate(_ id: Int) {
    Task.immediate { shown = await image(id) }
    print("Task.immediate  id=\(id) right after tap: \(shown)")
  }
}

@main
struct Main {
  static func main() async {
    let m = ImageModel()
    m.shown = "placeholder"; m.tapWithTask(1)
    try? await Task.sleep(for: .milliseconds(50))
    m.shown = "placeholder"; m.tapWithImmediate(1)
    m.shown = "placeholder"; m.tapWithImmediate(2)
    try? await Task.sleep(for: .milliseconds(50))
    print("later id=2: \(m.shown)")
  }
}
1
2
3
4
Task {}         id=1 right after tap: placeholder
Task.immediate  id=1 right after tap: cached-1
Task.immediate  id=2 right after tap: placeholder
later id=2: loaded-2

같은 캐시 적중(id 1)인데 Task {} 는 탭 직후에도 placeholder 이고, Task.immediate 는 탭 직후에 이미 cached-1 이다. 화면이 이 함수가 반환된 시점의 값을 그리면 Task {} 는 한 프레임 동안 placeholder 를 그린다. 그리고 캐시에 없는 id 2 는 Task.immediate 도 placeholder 로 시작한다. image(2) 가 실제로 멈추기 때문이고, 나중에 loaded-2 가 채운다. Task.immediate 는 빠른 경로가 있으면 이득이 있고, 없으면 Task {} 와 다르지 않다.


구독 순서를 보장하기

Andropov 의 사례(리뷰 #8)가 같은 이야기다. Task { for await ... } 로 구독을 시작한 뒤 바로 sequence.add(...) 를 부르면 task 가 아직 구독을 시작하지 않았을 수 있다. Task.immediate 는 구독이 첫 await 에 도달할 때까지 동기로 진행하므로, 이후의 add 가 구독 뒤에 일어난다. 여기서는 for await 가 첫 suspension 이 되고, 그 앞에서 구독 등록이 끝나 있다는 점이 중요하다. 이것은 구현이 구독을 next() 의 첫 호출에서 등록하는지에 달려 있어서, 모든 sequence 가 그렇다는 약속은 아니다(두 번째 리뷰 #6, ktoso).


프레임워크의 동기 마감에 맞추기

harlanhaskins 의 사례(리뷰 #7)는 UIKit 이 performDrop 이 끝나기 전에 로딩이 시작되길 요구하는 경우다. Task {} 로 시작하면 이 마감을 넘길 수 있고, Task.immediate 는 performDrop 안에서 NSItemProvider 의 로딩을 시작한다.


다른 선택지는 왜 안 됐나

대안은 제안서의 Alternatives Considered 와 스레드에서 나온 것을 묶는다.


isolation 을 동적으로 단언하기

MainActor.assumeIsolated 처럼 맞는지 단언하고 틀리면 멈추는 방식이다. 이 글의 Compose.swift 가 보여 준 대로 틀리면 프로세스가 죽고, 동기 closure 만 받으므로 async 함수를 부를 수 없다. Task.immediate 는 틀리면 enqueue 라서 안전하다. 두 도구는 겹쳐 쓸 수 있다(assumeIsolated 안에서 Task.immediate).


noasync 로 막기

Task.immediate 를 동기 컨텍스트에서만 부르게 하는 noasync 표시를 붙이는 안도 검토되었다. 그러나 async 함수 안에서도 구조화되지 않은 task 를 첫 suspension 까지 바로 돌리고 싶은 경우가 있어서 이 제한은 두지 않았다.


Task 의 기본으로 만들기

앞의 스레드 절에서 본 대로 John_McCall 이 막았다(리뷰 #60). 의미가 바뀌고, re-entrancy 가 생기고, 교착이 생길 수 있다. 기존 코드의 의미가 조용히 달라지는 변경이기도 하다.


별도 타입이나 옵션으로 표현하기

Task.init 에 옵션 파라미터를 더하는 안은 isolation 을 옵션으로 표현할 수 없어서 안 되었다(리뷰 #63, ktoso). 새 메서드를 두면 @_inheritActorContext(always) 같은 속성을 이 메서드에만 걸 수 있다.


다른 isolation 의 closure 를 막기

초안이 그랬던 안이다. 수정 요청에서 풀렸다. 막으면 컴파일러가 호출자와 closure 의 isolation 이 같은지를 정적으로 따져야 하는데, 이것은 @isolated(any) 와 동적 검사로 해결된다.


Swift 6 모드와 마이그레이션

이 API 는 기존 코드를 바꾸지 않고 선언만 더한다. source 호환과 ABI 에 영향이 없다. 다만 anyAppleOS 26.0 이라는 availability 가 붙어 있어서 배포 대상에 따라 쓸 수 있는 자리가 달라진다.


언어 모드에 따른 차이

Motivation.swift 의 오류가 Swift 5, Swift 5 complete, Swift 6 모드에서 같은 문구로 나왔다. modes.sh 는 세 모드로 같은 파일을 컴파일해서 출력을 비교하는 스크립트다. 이 제안에서 언어 모드를 타는 동작은 없다.


availability 와 back-deploy

@_alwaysEmitIntoClient 인데도 availability 가 붙어 있어서, macOS 14 를 대상으로 컴파일하면 이렇게 막힌다.

1
2
3
func start() {
  Task.immediate { print("x") }
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -target arm64-apple-macos14 Avail.swift
1
2
3
4
5
6
7
8
9
Avail.swift:2:8: error: 'immediate(name:priority:executorPreference:operation:)' is only available in macOS 26.0 or newer
1 | func start() {
  |      `- note: add '@available' attribute to enclosing global function
2 |   Task.immediate { print("x") }
  |        |- error: 'immediate(name:priority:executorPreference:operation:)' is only available in macOS 26.0 or newer
  |        `- note: add 'if #available' version check
3 | }
4 | 
[exit 1]

고치는 법은 컴파일러가 알려 준 대로 if #available 이다. AvailOK.swift 는 같은 target 에서 오류 없이 컴파일된다.

1
2
3
4
5
6
7
8
// macOS 14 을 지원하는 모듈에서 Task.immediate 를 쓰는 법
func start() {
  if #available(macOS 26.0, *) {
    Task.immediate { print("immediate") }
  } else {
    Task { print("Task") }
  }
}
1
[exit 0]

else 에서 Task {} 로 대신하는 것은 “바로 돈다” 를 포기하는 선택이다. 순서가 중요한 코드라면 이 fallback 이 같은 결과를 내지 않는다. 이전 OS 를 지원하면서 immediate 가 꼭 필요하면 이 API 를 쓸 수 없다.

if #available 로 OS 버전 나누기

#available(macOS 26.0, *) 는 지금 실행 중인 OS 가 26.0 이상인지를 실행 시점에 확인하는 조건이다. 참이면 그 안에서는 Task.immediate 를 컴파일러가 허용한다. 마지막 * 는 나열하지 않은 플랫폼에서는 참으로 보겠다는 뜻이다. 컴파일러의 노트가 제안한 두 방법(@available 로 함수 전체를 제한, if #available 로 일부만 제한) 중 후자다.


정리

  • Task.immediate, Task.immediateDetached, addImmediateTask 는 호출자의 executor 에서 첫 suspension 까지 바로 실행한다
  • suspension 은 task 가 carrier thread 를 내주는 순간이다. await 는 가능성일 뿐이다
  • 호출자의 isolation 과 closure 의 isolation 이 맞으면 바로, 맞지 않으면 enqueue 한다. 판정은 실행 시점에 하고, 이 글은 print 순서가 아니라 Mutex 플래그와 thread 번호로 확인했다
  • MainActor.assumeIsolated 는 틀리면 죽고 동기 closure 만 받는다. Task.immediate 는 틀리면 enqueue 하고 async 를 허용한다
  • closure 는 @_inheritActorContext(always) 로 호출자의 isolation 을 물려받는다. self 를 capture 하지 않아도 그렇다. 평범한 Task {} 는 @concurrent 가 될 수 있다
  • operation 은 sending 이고 @isolated(any) 다
  • 6.4 에서 immediateDetached closure 는 actor isolated 이고, actor 안 group 의 child closure 는 self 를 쓸 때만 actor isolated 이며, main actor 함수 안 group 의 addImmediateTask closure 는 MainActor 다
  • 순서 보장은 “내가 시작하는 순서” 까지다. actor 에 들어오는 task 들의 FIFO 는 약속하지 않는다

관련 글


참고자료

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