포스트

[SE-0410] Low-Level Atomic Operations

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


제안서 정보


한 줄 요약

Synchronization 모듈에 Atomic<Value> 가 들어온다. 여러 스레드가 같은 값을 락 없이 읽고 바꾸는 데 쓰는 타입이다. 이 글은 Atomic 이 어떻게 생겼는지, 왜 let 으로만 선언할 수 있는지, 왜 메모리 순서(ordering)를 상수로만 받는지를 컴파일해서 실행한 출력으로 정리한다. 두 번의 리뷰에서 모듈 이름, 프로토콜 이름, var 진단, Sendable 조건이 어떻게 정해졌는지도 스레드 원문으로 따라간다.


어떤 문제였나

여러 스레드에서 숫자 하나를 세려면 지금까지는 락을 잡거나 Dispatch 큐에 던져야 했다. 제안서는 그 사이를 메우는 도구를 말한다. 락 없이, 코드에 쓴 연산이 그대로 CPU 명령 하나로 나가는 타입이다. Motivation 은 세 가지를 요구한다. 어떤 연산이 atomic 인지 소스에 드러나야 하고, 락을 쓰지 않아야 하고, 가능하면 명령 하나로 끝나야 한다.


보통 var 로 세면 생기는 일

제안서 Motivation 의 예제를 그대로 돌렸다. 10 개 스레드가 각각 1_000_000 번씩 wrappingAdd(1, ordering: .relaxed) 로 더하고, 끝나면 값을 찍는다.

Counter.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 제안서 Motivation 예제: concurrentPerform 으로 10 x 1_000_000 번 wrappingAdd
import Dispatch
import Synchronization

@main
struct Main {
  static func main() {
    let counter = Atomic<Int>(0)
    DispatchQueue.concurrentPerform(iterations: 10) { _ in
      for _ in 0 ..< 1_000_000 {
        counter.wrappingAdd(1, ordering: .relaxed)
      }
    }
    print(counter.load(ordering: .relaxed))
  }
}

20 번을 돌렸고 20 번 모두 10000000 이 나왔다. 대조군은 같은 일을 보통 var 로 한 코드다.

PlainVar.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 대조군: 같은 일을 보통 var 로
import Dispatch

@main
struct Main {
  static func main() {
    var counter = 0
    DispatchQueue.concurrentPerform(iterations: 10) { _ in
      for _ in 0 ..< 1_000_000 {
        counter += 1
      }
    }
    print(counter)
  }
}

이 코드는 Swift 6 모드에서 error 가 아니라 warning 하나로 컴파일된다.

1
10:9: warning: mutation of captured var 'counter' in concurrently-executing code [#SendableClosureCaptures]

20 번을 돌렸더니 값이 매번 달랐고 20 번 모두 10000000 보다 작았다. 이 머신의 20 번은 2639366 부터 4525251 사이였다. 같은 코드를 다시 돌린 다른 두 번의 측정은 3316640 부터 6581062 사이, 2631771 부터 6656958 사이였다. 여러 스레드가 같은 칸을 읽고 쓰다 서로의 덧셈을 덮어쓴 결과다. 돌릴 때마다 범위가 달라지고, 변하지 않는 것은 “1천만이 나오지 않는다” 는 점이다.

같은 1천만 번 더하기를 Atomic 으로 20번 돌리면 매번 10,000,000 이 나오고 보통 var 로 20번 돌리면 매번 다른 값이 나온다는 것을 보여 주는 그림

위쪽 20 개는 Atomic 으로 센 20 번이고 모두 꽉 찬 막대다. 아래쪽 20 개는 보통 var 로 센 20 번이고 막대 높이가 목표값 대비 비율이다.

왜 warning 인지도 가려 봤다. Dispatch interface 에서 concurrentPerform 의 선언이 @preconcurrency 다.

1
@preconcurrency public class func concurrentPerform(iterations: Swift::Int, execute work: @Sendable (Swift::Int) -> Swift::Void)

같은 모양이지만 @preconcurrency 가 없는 함수로 바꾼 PlainVarSendable.swift 는 error 였다.

1
7:34: error: mutation of captured var 'counter' in concurrently-executing code [#SendableClosureCaptures]

@preconcurrency 만 붙이고 나머지는 똑같이 만든 PlainVarPre.swift 는 같은 자리가 warning 이었다.

1
2
3
4
5
6
7
8
9
10
// 대조군: @preconcurrency 만 붙인 같은 모양의 함수
@preconcurrency
func perform(iterations: Int, execute work: @Sendable (Int) -> Void) {
  for i in 0 ..< iterations { work(i) }
}
func f() -> Int {
  var counter = 0
  perform(iterations: 10) { _ in counter += 1 }
  return counter
}
1
8:34: warning: mutation of captured var 'counter' in concurrently-executing code [#SendableClosureCaptures]

@main 안에서 부르는 모양으로 바꿔도 같았다. 속성이 없는 PlainVarMainSendable.swift 는 9:36 이 error 였고, @preconcurrency 를 붙인 PlainVarMainPre.swift 는 10:36 이 warning 이었다. 같은 코드에서 @preconcurrency 하나가 error 와 warning 을 가른다.

TaskGroup 의 addTask 에서 var counter 를 고치려는 PlainVarTask.swift 도 error 다.

1
2
8:15: error: passing closure as a 'sending' parameter risks causing data races between main actor-isolated code and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
note: closure captures 'counter' which is accessible to main actor-isolated code

이 진단이 나오는 규칙은 SE-0414 에서 따로 다뤘다. Dispatch 처럼 옛 API 는 warning 으로 넘어가지만 Task 쪽은 막힌다. 지역 let hits = Atomic<Int>(0) 을 addTask 8 개가 잡아 각각 100_000 번 더하는 TaskCapture.swift 는 진단 없이 컴파일됐고 20 번 모두 800000 이었다.


락이 아니라 명령 하나

~/se0410/counter 를 objdump -d 로 열어 보면 relaxed wrappingAdd 가 ldadd x8, x8, [x9] 한 줄이다. 락을 잡고 푸는 코드가 없다. 이것이 Motivation 의 세 번째 요구, “명령 하나” 다.


무엇이 바뀌나

더해지는 것은 Atomic<Value>, 메모리 순서 세 가지, atomicMemoryFence, AtomicRepresentable 과 AtomicOptionalRepresentable, 128 비트 값을 다루는 WordPair, 그리고 AtomicLazyReference 다. 모두 import Synchronization 을 써야 보인다. 쓰지 않은 NoImport.swift 는 Atomic 이름이 없다고 한다.

1
2
3
4
func f() {
  let a = Atomic<Int>(0)
  _ = a.load(ordering: .relaxed)
}
1
2:11: error: cannot find 'Atomic' in scope

Atomic 의 모양

Swift 6.4 SDK 의 Synchronization.swiftmodule 에서 arm64e-apple-macos.swiftinterface 를 열어 선언을 옮겼다. 거의 모든 선언에 @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) 가 붙어 있고, 아래에서는 읽기 쉽게 줄였다.

1
2
3
4
5
6
@frozen @_rawLayout(like: Value.AtomicRepresentation) @_staticExclusiveOnly public struct Atomic<Value> : ~Swift::Copyable where Value : Synchronization::AtomicRepresentable {
  @_alwaysEmitIntoClient @_transparent public init(_ initialValue: consuming Value)
  @_alwaysEmitIntoClient @inlinable deinit
}
extension Synchronization::Atomic : @unchecked Swift::Sendable where Value : Swift::Sendable {
}
  • ~Copyable 이라 복사할 수 없다. 두 곳에서 같은 값을 쥔 채 따로 바꾸는 일이 애초에 불가능하다.
  • @_rawLayout(like: Value.AtomicRepresentation) 은 저장 공간이 Value 의 atomic 표현과 같은 크기와 정렬이라는 뜻이다. 값이 힙에 따로 올라가지 않고 Atomic 이 놓인 자리에 그대로 있다.
  • 연산은 @_alwaysEmitIntoClient @_transparent 라서 호출하는 쪽 실행 파일에 명령이 직접 들어간다. 위의 ldadd 가 그 결과다.
  • Sendable 은 Value 가 Sendable 일 때만 성립한다. 이유는 뒤에서 본다.

Atomic

Atomic은 한 값을 락 없이 읽고 바꾸는 타입이다. 복사할 수 없고, 연산마다 메모리 순서를 인자로 받는다.


복사와 이동

Atomic 은 복사할 수 없는 타입이라 let b = a 는 복사가 아니라 이동이다. Copy.swift 에서 let b = a 뒤에 a 를 다시 썼더니 error 가 났다.

1
2
3
3:7: error: 'a' used after consume
note: consumed here
note: used here

b 만 쓰고 consuming 인자로 넘기는 Move.swift 는 진단이 없었다. 지역 let a 를 escape 하는 closure 가 잡아서 wrappingAdd 를 부르는 Capture.swift 도 진단이 없었다.


let 만 허용하는 규칙

이 제안서의 핵심 규칙이다. Atomic 은 var 로 선언하면 컴파일되지 않는다. 지역 변수에서 VarLocal.swift 를 컴파일했다.

1
2
3
4
5
import Synchronization
func f() {
  var myAtomic = Atomic<Int>(123)
  _ = myAtomic.load(ordering: .relaxed)
}
1
2
3:7: error: variable of type 'Atomic<Int>' must be declared with a 'let'
warning: variable 'myAtomic' was never mutated; consider changing to 'let' constant [#VariableNeverMutated]

-swift-version 5 로 컴파일해도 같은 error 가 났다. 같은 error 가 나는 자리는 전역 변수(VarGlobal.swift), class 의 저장 프로퍼티(VarClass.swift), struct 의 저장 프로퍼티(StructField.swift), computed property(Computed.swift) 다. 전역 변수에서는 error 가 둘 나온다. 하나는 Atomic 의 let 요구이고, 다른 하나는 nonisolated 전역 var 가 안전하지 않다는 진단이다.

1
2
error: var 'globalAtomic' is not concurrency-safe because it is nonisolated global shared mutable state [#MutableGlobalVariable]
error: variable of type 'Atomic<Int>' must be declared with a 'let'

인자로 넘길 때는 소유권을 적어야 한다. InoutParam.swift 의 inout 은 error 였다.

1
2:17: error: parameter of type 'Atomic<Int>' must be declared as either 'borrowing' or 'consuming'

아무것도 적지 않은 func plain(_ a: Atomic<Int>) 는 복사할 수 없는 타입에 대한 일반 진단이 나오는데, note 가 막혀 있는 inout 까지 권한다.

1
2
3
4
5:17: error: parameter of noncopyable type 'Atomic<Int>' must specify ownership
note: add 'borrowing' for an immutable reference
note: add 'inout' for a mutable reference
note: add 'consuming' to take the value from the caller

Atomic 의 extension 에 mutating 메서드를 넣는 것도 막힌다(Mutating.swift).

1
3:3: error: type 'Atomic<Value>' cannot have mutating function 'greet()'

AtomicLazyReference 도 같은 규칙을 따른다. var 로 둔 LazyDocVar.swift 는 같은 error 다.

1
5:7: error: variable of type 'AtomicLazyReference<Histogram>' must be declared with a 'let'

왜 let 이어야 하나

let 으로 선언한 Atomic 의 값이 바뀌는 것이 이상하게 보인다. 제안서가 var 를 막는 이유는 동적 exclusivity 검사다. var 프로퍼티에 접근하면 컴파일러는 그 접근이 겹치지 않는지 실행 중에 확인하는 코드를 붙인다. 그러면 접근이 “순수한 atomic 접근” 이 아니게 된다. 이것을 SIL(Swift 컴파일러가 만드는 중간 코드)로 직접 봤다.

대조군은 let 으로 선언한 Atomic 을 가진 class 다.

LetFieldSIL.swift

1
2
3
4
5
import Synchronization
final class Box2 {
  let a = Atomic<Int>(0)
  func bump() -> Int { a.wrappingAdd(1, ordering: .relaxed).newValue }
}

이 파일에는 @main 이 없어서 -O 로 SIL 을 뽑으면 bump 가 쓰이지 않는 함수로 지워진다. 그래서 먼저 최적화를 끄고(-Onone) 뽑았다.

1
xcrun swiftc -emit-sil -Onone -o /tmp/lf0.sil -parse-as-library -wmo -swift-version 6 LetFieldSIL.swift

bump 안에서 추린 줄은 이렇다.

1
2
3
%3 = ref_element_addr [immutable] %0, #Box2.a
(addressOfRawLayout)
atomicrmw_add_monotonic_Int64

ref_element_addr [immutable] 로 field 주소를 얻고 바로 atomic 명령으로 간다. begin_access 가 없다.

-O 는 bump 를 두 번 부르는 LetFieldMain.swift 로 따로 봤다.

1
2
3
4
5
6
7
8
9
10
11
import Synchronization
final class Box2 {
  let a = Atomic<Int>(0)
  func bump() -> Int { a.wrappingAdd(1, ordering: .relaxed).newValue }
}
@main struct Main {
  static func main() {
    let b = Box2()
    print(b.bump(), b.bump())
  }
}

같은 명령에서 -Onone 대신 -O 를 줘서 뽑은 SIL 에는 begin_access 가 0 개, ref_element_addr [immutable] 이 1 개, atomicrmw_add_monotonic_Int64 가 2 개 있었다. 최적화를 켜도 let 필드는 검사 없이 atomic 명령만 남는다.

이제 규칙이 덮지 않는 곳을 보자. Atomic 을 let 으로 가진 복사 불가 struct 를 만들고, 그 struct 를 class 의 var 로 두었다.

NestedVarOnly.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Synchronization
struct Holder: ~Copyable {
  let a = Atomic<Int>(0)
}
final class Box {
  var h = Holder()
  func bump() -> Int { h.a.wrappingAdd(1, ordering: .relaxed).newValue }
}
@main struct Main {
  static func main() {
    let b = Box()
    print(b.bump(), b.bump())
  }
}

bash diag.sh NestedVarOnly.swift 는 [exit 0] 하나만 찍는다. 진단이 없다. 같은 명령으로 SIL 을 뽑으면 bump 안이 다르다.

1
2
3
4
5
%3 = ref_element_addr %0, #Box.h
%4 = begin_access [read] [dynamic] %3
%5 = struct_element_addr %4, #Holder.a
(addressOfRawLayout)
atomicrmw_add_monotonic_Int64

atomic 명령 앞에 begin_access [read] [dynamic] 이 붙었다. -O 로 뽑아도 begin_access 가 1 개 남았고 atomicrmw_add_monotonic_Int64 는 2 개였다. 같은 모양으로 bump 를 두 번 부른 LetFieldMain.swift 가 검사 0 개였던 것과 대비된다. 컴파일러는 이 경우를 막지 않지만 var 가 부르는 동적 검사 비용은 그대로 치른다는 뜻이다. 제안서가 var 를 막으려던 바로 그 비용이다. 두 번째 리뷰에서 pyrtsa 가 Atomic 을 품은 struct 를 var 로 두는 것도 막느냐고 물은 것이 이 경우다(#29).

let 으로 둔 Atomic 은 atomic 명령만 남고 var 를 거치는 Atomic 은 그 앞에 동적 exclusivity 검사가 붙는다는 것을 보여 주는 그림

왼쪽은 LetFieldSIL.swift(-Onone), 오른쪽은 NestedVarOnly.swift 에서 뽑은 SIL 이다. 아래 점선 칸은 var a: Atomic<Int> 처럼 직접 쓰면 컴파일 단계에서 error 라는 뜻이다.


연산 전체

Ops.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
import Synchronization

@main
struct Main {
  static func main() {
    let a = Atomic<Int>(10)
    print("load", a.load(ordering: .acquiring))
    a.store(20, ordering: .releasing)
    print("exchange old", a.exchange(30, ordering: .acquiringAndReleasing))
    let r1 = a.compareExchange(expected: 30, desired: 40, ordering: .sequentiallyConsistent)
    print("cas hit", r1)
    let r2 = a.compareExchange(expected: 30, desired: 50, ordering: .relaxed)
    print("cas miss", r2)
    let r3 = a.compareExchange(expected: 40, desired: 41, successOrdering: .acquiring, failureOrdering: .relaxed)
    print("cas 2 orderings", r3)
    var weakTries = 0
    var cur = a.load(ordering: .relaxed)
    while true {
      weakTries += 1
      let (ok, orig) = a.weakCompareExchange(expected: cur, desired: cur * 2, ordering: .relaxed)
      if ok { break }
      cur = orig
    }
    print("weak cas tries", weakTries, "value", a.load(ordering: .relaxed))
    print("wrappingAdd", a.wrappingAdd(1, ordering: .relaxed))
    print("wrappingSubtract", a.wrappingSubtract(3, ordering: .relaxed))
    print("bitwiseAnd", a.bitwiseAnd(0xF0, ordering: .relaxed))
    print("bitwiseOr", a.bitwiseOr(0x0F, ordering: .relaxed))
    print("bitwiseXor", a.bitwiseXor(0xFF, ordering: .relaxed))
    print("add", a.add(5, ordering: .relaxed))
    print("subtract", a.subtract(5, ordering: .relaxed))
    let counter = Atomic<Int>(100)
    print("max", counter.max(82, ordering: .relaxed).oldValue, counter.max(182, ordering: .relaxed))
    print("min", counter.min(7, ordering: .relaxed))
    let tracker = Atomic<Bool>(false)
    print("logicalOr", tracker.logicalOr(true, ordering: .relaxed).newValue)
    print("logicalAnd", tracker.logicalAnd(false, ordering: .relaxed))
    print("logicalXor", tracker.logicalXor(true, ordering: .relaxed))
    let big = Atomic<Int>(.max)
    print("wrap at max", big.wrappingAdd(1, ordering: .relaxed))
    atomicMemoryFence(ordering: .relaxed)
    atomicMemoryFence(ordering: .sequentiallyConsistent)
    print("fence ok")
    print("orderings", AtomicLoadOrdering.acquiring, AtomicUpdateOrdering.acquiringAndReleasing, AtomicStoreOrdering.releasing)
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
load 10
exchange old 20
cas hit (exchanged: true, original: 30)
cas miss (exchanged: false, original: 40)
cas 2 orderings (exchanged: true, original: 40)
weak cas tries 1 value 82
wrappingAdd (oldValue: 82, newValue: 83)
wrappingSubtract (oldValue: 83, newValue: 80)
bitwiseAnd (oldValue: 80, newValue: 80)
bitwiseOr (oldValue: 80, newValue: 95)
bitwiseXor (oldValue: 95, newValue: 160)
add (oldValue: 160, newValue: 165)
subtract (oldValue: 165, newValue: 160)
max 100 (oldValue: 100, newValue: 182)
min (oldValue: 182, newValue: 7)
logicalOr true
logicalAnd (oldValue: true, newValue: false)
logicalXor (oldValue: false, newValue: true)
wrap at max (oldValue: 9223372036854775807, newValue: -9223372036854775808)
fence ok
orderings acquiring acquiringAndReleasing releasing

max 와 logicalOr 줄은 제안서 예제(counter.max(82, ordering: .relaxed).oldValue, tracker.logicalOr(true, ordering: .relaxed).newValue)를 그대로 쓴 것이다.

load, store, exchange

load 는 값을 읽고 store 는 값을 쓴다. exchange 는 새 값을 넣고 이전 값을 돌려준다. 메모리 순서는 load 에 AtomicLoadOrdering, store 에 AtomicStoreOrdering, 나머지에는 AtomicUpdateOrdering 을 준다.

compareExchange

compareExchange(expected:desired:ordering:) 는 지금 값이 expected 와 같으면 desired 로 바꾸고, 같지 않으면 아무것도 바꾸지 않는다. 결과는 (exchanged:, original:) 튜플이다. 위에서 cas hit 은 30 을 기대했고 실제로 30 이라서 바뀌었고, cas miss 는 30 을 기대했지만 실제로는 40 이라서 바뀌지 않고 40 을 돌려줬다. 성공할 때와 실패할 때의 순서를 따로 주는 형태(successOrdering:failureOrdering:)와 weakCompareExchange 도 있다. 스레드에서 이 이름은 C++11 에서 쓰는 용어를 따른 것이라고 lorentey 가 설명했다(첫 리뷰 #13, 2023-10-26). swift-atomics 와 SE-0282 와 맞추려는 선택이기도 하다.

wrappingAdd 와 add

정수 Atomic 에는 wrappingAdd, wrappingSubtract, bitwiseAnd, bitwiseOr, bitwiseXor, min, max, add, subtract 가 있고, Bool 에는 logicalAnd, logicalOr, logicalXor 가 있다. 모두 (oldValue:, newValue:) 를 돌려주고 @discardableResult 다. 이름의 “wrapping” 은 넘치면 반대편으로 감긴다는 뜻이다. 출력의 wrap at max 가 Int.max 에 1 을 더해 Int.min 으로 감긴 줄이다.

atomicMemoryFence

atomicMemoryFence(ordering:) 는 값 없이 순서만 세우는 울타리다. .relaxed 는 아무 제약도 걸지 않는데도 허용된다. interface 의 구현은 switch ordering { case .relaxed: return case .acquiring: Builtin.fence_acquire() ... 로 시작해서 .relaxed 면 그냥 돌아온다. wadetregaskis 는 거의 아무 일도 안 하는 .relaxed 를 허용하는 것이 탐탁지 않고 초보자가 헷갈릴 수 있다고 했다(첫 리뷰 #7). 해가 없는 no-op 이라 그대로 허용됐다.


add 의 넘침 trap

add 와 subtract 는 넘침을 trap 으로 처리한다. interface 에서 add 의 본문을 옮겼다.

1
2
3
4
5
6
7
var result = (exchanged: false, original: load(ordering: .relaxed))
var new: Int
repeat {
  new = result.original + operand
  result = weakCompareExchange(expected: result.original, desired: new, ordering: ordering)
} while !result.exchanged
return (oldValue: result.original, newValue: new)

weakCompareExchange 를 도는 반복문이다. new = result.original + operand 의 덧셈이 weakCompareExchange 보다 앞에 있다. 그래서 넘치면 이 덧셈에서 멈추고 저장은 일어나지 않는다. Overflow.swift 로 봤다.

1
2
3
4
5
6
7
8
9
10
import Synchronization
@main
struct Main {
  static func main() {
    let big = Atomic<Int>(.max)
    print("before")
    print(big.add(1, ordering: .relaxed))
    print("after", big.load(ordering: .relaxed))
  }
}

그냥 실행하면 exit 133 으로 끝나고 after 는 찍히지 않는다. 출력을 파이프로 넘기면 before 도 안 보인다. 멈추기 전에 버퍼에 있던 글자가 비워지지 않아서다. -g 로 컴파일해서 lldb 에서 돌리면 멈춘 이유가 나온다.

1
2
stop reason = Swift runtime failure: arithmetic overflow
frame #1 ... static Main.main() at Overflow.swift:7:15

7 번째 줄 big.add(1, ordering: .relaxed) 에서 멈췄다. wrappingAdd 는 같은 값에서 -9223372036854775808 로 감긴다(Ops.swift 의 wrap at max). 어느 쪽이 맞는지는 쓰는 쪽이 고른다. 카운터가 넘칠 일이 없으면 add 가 버그를 잡아 주고, 감겨도 괜찮으면 wrappingAdd 가 명령 하나로 끝난다.


ordering 은 상수만

메모리 순서는 호출하는 자리에 .relaxed 처럼 static 멤버를 직접 써야 한다. 제안서의 예제를 그대로 컴파일했다. 6.4 에 같은 이름의 add 가 있어서 이름만 add2 로 바꿨다.

DynOrdering.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 제안서 예제 그대로: 바깥에서 받은 ordering 을 compareExchange 에 넘긴다
import Synchronization

extension Atomic where Value == Int {
  // Non-inlinable
  public func add2(_ operand: Int, ordering: AtomicUpdateOrdering) {
    var done = false
    var current = load(ordering: .relaxed)

    while !done {
      (done, current) = compareExchange(
        expected: current,
        desired: current + operand, // Traps on overflow
        ordering: ordering
      )
    }
  }
}
1
14:19: error: ordering argument must be a static method or property of 'AtomicUpdateOrdering'

바깥에서 받은 ordering 을 안쪽 compareExchange 에 넘기는 순간 거부된다. 지역 let local: AtomicLoadOrdering = .relaxed, 전역 let globalOrdering = AtomicLoadOrdering.acquiring, flag ? .relaxed : .acquiring 도 DynOrdering2.swift 에서 모두 같은 error 였다(AtomicLoadOrdering 에 대해 error 3 개). @_transparent 로 감싼 DynOrdering3.swift 도 같은 error 다. 표준 라이브러리가 정의한 상수만 받고, 그것을 호출하는 자리에 직접 써야 한다. OrdMine.swift 에서 AtomicLoadOrdering 에 값이 .relaxed 인 static var mine 을 직접 만들어 a.load(ordering: .mine) 에 넘겼더니 거부됐다.

1
4:63: error: ordering argument must be a static method or property of 'AtomicLoadOrdering'

같은 파일에서 AtomicLoadOrdering.relaxed 로 풀어 쓴 호출은 통과했다. interface 의 연산에는 @_semantics("atomics.requires_constant_orderings") 가 붙어 있다.

기본 순서가 필요하면 직접 정의한 overload 로 감싸면 된다. DynOrdering4.swift 의 func load() -> Int { load(ordering: .sequentiallyConsistent) } 는 진단이 없었다.

이 규칙은 제안서의 Alternatives 에서 나왔다. 순서마다 메서드 이름을 따로 만드는 안, 순서를 generic 인자로 받는 안, ordering view 를 두는 안이 있었다. view 안은 API 면적이 구조체 6 개와 메서드 53 개에서 구조체 27 개와 메서드 175 개로 불어난다고 제안서가 적었다.


사용자 정의 타입

AtomicRepresentable 은 타입이 atomic 값이 되는 길이다. RawRepresentable 은 기본 구현이 있다. 제안서의 MyState 를 그대로 돌렸다.

State.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
// 제안서 예제: RawRepresentable enum 의 기본 구현
import Synchronization

enum MyState: Int, AtomicRepresentable {
  case starting
  case running
  case stopped
}

@main
struct Main {
  static func main() {
    let currentState = Atomic<MyState>(.starting)
    if currentState.compareExchange(
      expected: .starting,
      desired: .running,
      ordering: .sequentiallyConsistent
    ).exchanged {
      print("starting -> running")
    }
    let second = currentState.compareExchange(expected: .starting, desired: .running, ordering: .sequentiallyConsistent)
    print("second", second)
    currentState.store(.stopped, ordering: .sequentiallyConsistent)
    print(currentState.load(ordering: .sequentiallyConsistent))
    print(MemoryLayout<MyState>.size, MemoryLayout<Atomic<MyState>>.size, MemoryLayout<Atomic<MyState>>.alignment)
  }
}
1
2
3
4
starting -> running
second (exchanged: false, original: state.MyState.running)
stopped
1 8 8

MyState 는 1 바이트인데 Atomic<MyState> 는 8 바이트에 정렬 8 이다. 표현이 Int 의 것을 빌려 오기 때문이다. state.MyState 의 앞 글자는 바이너리 이름(-o state)이 모듈 이름이 된 것이다.

AtomicRepresentation 에는 BitwiseCopyable 이 요구된다. String 을 쓴 BadRepr.swift 는 이렇다.

1
2
error: type 'Weird' does not conform to protocol 'AtomicRepresentable'
note: possibly intended match 'Weird.AtomicRepresentation' (aka 'String') does not conform to 'BitwiseCopyable'

AtomicRepresentable

AtomicRepresentable은 값을 atomic 저장소 타입으로 바꾸고 되돌리는 두 함수(encodeAtomicRepresentation, decodeAtomicRepresentation)를 요구하는 프로토콜이다. Atomic<Value> 의 연산 가운데 load 와 compareExchange 같은 것은 AtomicRepresentation 이 8 비트부터 128 비트까지의 원시 저장소(_Atomic8BitStorage 부터 _Atomic128BitStorage)일 때만 보인다.


포인터와 내 타입

포인터를 품은 타입은 AtomicOptionalRepresentable 로 nil 까지 담는다. 제안서의 MyPointer 에서 somePointer 만 채워 돌렸다.

MyPointer.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
import Synchronization

struct MyPointer: RawRepresentable, AtomicOptionalRepresentable {
  var rawValue: UnsafeRawPointer

  init(rawValue: UnsafeRawPointer) {
    self.rawValue = rawValue
  }
}

@main
struct Main {
  static func main() {
    let buf = UnsafeMutableRawPointer.allocate(byteCount: 8, alignment: 8)
    defer { buf.deallocate() }
    let somePointer = UnsafeRawPointer(buf)
    let myAtomicPointer = Atomic<MyPointer?>(nil)
    if myAtomicPointer.compareExchange(
      expected: nil,
      desired: MyPointer(rawValue: somePointer),
      ordering: .relaxed
    ).exchanged {
      print("stored", myAtomicPointer.load(ordering: .relaxed)!.rawValue == somePointer)
    }
    myAtomicPointer.store(nil, ordering: .releasing)
    print("after nil", myAtomicPointer.load(ordering: .acquiring) == nil)
    print(MemoryLayout<Atomic<MyPointer?>>.size)
  }
}
1
2
3
stored true
after nil true
8

Int 의 표현을 빌려 쓰는 MyCoolInt 도 돌렸다(MyCoolInt.swift). 출력은 MyCoolInt(x: 1) MyCoolInt(x: 2) 다. 다만 표현만 빌려서는 산술 연산이 생기지 않는다. wrappingAdd 는 Value == Int 일 때만 있어서 MyCoolIntNoOps.swift 에서 이렇게 막혔다.

1
2
9:46: error: referencing instance method 'wrappingAdd(_:ordering:)' on 'Atomic' requires the types 'MyCoolInt' and 'Int' be equivalent
note: where 'Value' = 'MyCoolInt'

AtomicRepresentation 을 Int 로 썼지만 원시 저장소가 아닌 타입(BadRepr2.swift)은 conformance 와 Atomic<Weird2>(...) 생성까지는 통과하고 load 에서 걸린다.

1
9:47: error: no exact matches in call to instance method 'load'

note 로 후보 다섯 개(_Atomic8BitStorage, 16, 32, 64, 128)가 붙는다.


WordPair 와 128 비트 CAS

WordPair 는 UInt 두 개(first, second)를 묶은 구조체이고 atomic 저장소가 128 비트다. 값과 버전 번호를 한 번에 바꾸는 데 쓴다. 다른 스레드가 값을 A 에서 B 로 바꿨다가 A 로 되돌리면 값만 비교하는 compare-exchange 는 아무 일도 없었다고 착각한다. 이것이 ABA 문제이고, 버전 번호를 같이 바꾸면 피할 수 있다.

WordPair.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
// 128bit CAS: 값과 버전 번호를 한 번에 바꾼다
import Dispatch
import Synchronization

@main
struct Main {
  static func main() {
    print(MemoryLayout<WordPair>.size, MemoryLayout<WordPair>.alignment,
          MemoryLayout<Atomic<WordPair>>.size, MemoryLayout<Atomic<WordPair>>.alignment)
    let slot = Atomic<WordPair>(WordPair(first: 0, second: 0))
    DispatchQueue.concurrentPerform(iterations: 8) { _ in
      for _ in 0 ..< 100_000 {
        var cur = slot.load(ordering: .relaxed)
        while true {
          let next = WordPair(first: cur.first &+ 1, second: cur.second &+ 2)
          let (ok, orig) = slot.weakCompareExchange(expected: cur, desired: next, ordering: .relaxed)
          if ok { break }
          cur = orig
        }
      }
    }
    let end = slot.load(ordering: .relaxed)
    print(end, end.second == end.first * 2)
    print(Atomic<Duration>.self, MemoryLayout<Atomic<Duration>>.size)
    let d = Atomic<Duration>(.seconds(1))
    print(d.exchange(.milliseconds(5), ordering: .relaxed), d.load(ordering: .relaxed))
  }
}

20 번을 돌렸고 20 번 모두 같은 네 줄이 나왔다.

1
2
3
4
16 8 16 16
WordPair(first: 800000, second: 1600000) true
Atomic<Duration> 16
1.0 seconds 0.005 seconds

8 개 스레드가 first 는 1, second 는 2 씩 올렸는데 두 칸이 한 번에 바뀌어서 second 가 언제나 first 의 두 배였다. WordPair 는 16 바이트에 정렬 8 이고 Atomic<WordPair> 는 16 바이트에 정렬 16 이다. Duration 도 WordPair 표현을 써서 16 바이트다.

-O 로 빌드한 실행 파일을 objdump -d 로 열면 casp x2, x3, x4, x5, [x22] 와 casp x4, x5, x2, x3, [x9] 가 있다. 128 비트 compare-and-swap 명령이다.

WordPair 의 Comparable 은 macOS 15.4 부터다. -target arm64-apple-macos15.0 으로 a < b 를 쓴 WordPairCmp.swift 는 이렇다.

1
3:52: error: conformance of 'WordPair' to 'Comparable' is only available in macOS 15.4 or newer

-target 을 15.4 로 올리면 진단이 없었다. 이 일은 아래 스레드 절에서 이어진다.

WordPair

WordPair는 first 와 second 두 UInt 를 가진 구조체다. AtomicRepresentable, Equatable, Hashable, Comparable(macOS 15.4 부터), CustomStringConvertible, CustomDebugStringConvertible, BitwiseCopyable, Sendable 을 따른다.


AtomicLazyReference

AtomicLazyReference<Instance> 는 객체 하나를 처음 필요할 때 만들어 두는 칸이다. init() 만 있고 인자가 없다. 메서드는 storeIfNil 과 load 둘이다. interface 에서는 storeIfNil 과 load 가 별도 extension 에 있고 storage 에 @usableFromInline 이 붙어 있는데, 아래에서는 한 선언으로 줄였다.

1
2
3
4
5
6
7
8
@frozen @_staticExclusiveOnly @safe public struct AtomicLazyReference<Instance> : ~Swift::Copyable where Instance : AnyObject {
  internal let storage: Synchronization::Atomic<Swift::Unmanaged<Instance>?>
  @inlinable public init()
  public func storeIfNil(_ desired: consuming Instance) -> Instance
  public func load() -> Instance?
}
extension Synchronization::AtomicLazyReference : @unchecked Swift::Sendable where Instance : Swift::Sendable {
}

초기값을 넘기는 AtomicLazyReference<Foo>(Foo()) 는 LazyInit.swift 에서 이렇게 막혔다.

1
3:34: error: argument passed to call that takes no arguments

제안서의 atomicLazyFoo 모양을 그대로 쓰되, 몇 번 만들어졌는지를 Atomic<Int> 로 세고 본 인스턴스가 몇 가지인지를 Mutex 로 모았다.

Lazy.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
// AtomicLazyReference: 여러 스레드가 동시에 만들어도 한 개만 남는다
import Dispatch
import Synchronization

final class Foo: Sendable {
  let id: Int
  init(id: Int) { self.id = id }
}

let made = Atomic<Int>(0)
let _foo = AtomicLazyReference<Foo>()

// This is safe to call concurrently from multiple threads.
var atomicLazyFoo: Foo {
  if let foo = _foo.load() { return foo }
  // Note: the code here may run concurrently on multiple threads.
  // All but one of the resulting values will be discarded.
  let foo = Foo(id: made.wrappingAdd(1, ordering: .relaxed).newValue)
  return _foo.storeIfNil(foo)
}

@main
struct Main {
  static func main() {
    let seen = Mutex<Set<ObjectIdentifier>>([])
    DispatchQueue.concurrentPerform(iterations: 16) { _ in
      let f = atomicLazyFoo
      seen.withLock { _ = $0.insert(ObjectIdentifier(f)) }
    }
    print("made", made.load(ordering: .relaxed), "distinct seen", seen.withLock { $0.count }, "id", atomicLazyFoo.id)
  }
}

30 번을 돌렸다. distinct seen 1 은 30 번 모두였고, 이번 30 번에서 made 는 1 에서 9 까지 바뀌었고 남은 인스턴스의 id 는 1 에서 4 사이였다. 다시 돌리면 범위가 조금씩 달랐다(다른 두 번에서는 made 1 에서 8, id 1 에서 3). 여러 스레드가 동시에 만들 수는 있지만 하나만 남는다는 말이 그대로 보인다. 이것은 weak 가 아니라 strong reference 라서 만든 것이 계속 살아 있다. lorentey 가 이 점을 정리했다. 장점은 막히는 스레드가 없다는 것이고 단점은 같은 일을 여러 번 할 수 있다는 것이다(첫 리뷰 #10, 10-26).

var 로 둔 AtomicLazyReference 는 위에서 본 것처럼 error 다. 문서 주석의 _histogram 예제 모양이 그 경우다(LazyDocVar.swift).

AtomicLazyReference

AtomicLazyReference는 storeIfNil 로 처음 넣은 객체만 남기고 load 로 읽는 칸이다. storeIfNil 은 이미 값이 있으면 넣으려던 것을 버리고 남아 있는 것을 돌려준다.


Sendable 조건

Atomic 은 Value 가 Sendable 일 때만 Sendable 이다. SendablePtr.swift 에서 세 경우를 Sendable class 의 저장 프로퍼티로 넣었다.

1
2
3
4
5
6
7
8
9
10
11
12
// Atomic 이 Sendable 인 조건: Value 가 Sendable 일 때만
import Synchronization
final class IntBox: Sendable {
  let n = Atomic<Int>(0)
}
final class PtrBox: Sendable {
  let p = Atomic<UnsafeMutableRawPointer?>(nil)
}
final class NonSendable { var x = 0 }
final class RefBox: Sendable {
  let r = AtomicLazyReference<NonSendable>()
}

IntBox 는 통과했다. 나머지 둘은 error 다.

1
2
3
4
7:7: error: stored property 'p' of 'Sendable'-conforming class 'PtrBox' has non-Sendable type 'Atomic<UnsafeMutableRawPointer?>'
note: generic struct 'Atomic' does not conform to the 'Sendable' protocol
11:7: error: stored property 'r' of 'Sendable'-conforming class 'RefBox' contains non-Sendable type 'NonSendable'
note: class 'NonSendable' does not conform to the 'Sendable' protocol

AtomicLazyReference 도 Instance 가 Sendable 일 때만 @unchecked Sendable 이라서 RefBox 의 error 가 NonSendable 을 가리킨다. 포인터는 Sendable 이 아니라서 Atomic<UnsafeMutableRawPointer?> 도 Sendable 이 아니다. Task 로 잡으려는 TaskCapturePtr.swift 도 막힌다.

1
2
6:11: error: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
note: closure captures reference to mutable let 'p' which remains modifiable by code in the current isolation context

컴파일러가 이 let 을 “mutable let” 이라 부른다. 값이 안에서 바뀌는 let 이라는 사정이 진단 문구에까지 나온다.

이 조건이 왜 붙었는지는 스레드에서 갈렸다. 아래 절에서 다룬다.


availability

타입, conformance, 연산이 모두 macOS 15 부터다. -target arm64-apple-macos14 로 Avail14.swift 를 컴파일하면 error 가 다섯 개 나온다.

1
2
3
4
5
3:11: error: 'Atomic' is only available in macOS 15.0 or newer
3:21: error: 'init(_:)' is only available in macOS 15.0 or newer
3:7: error: conformance of 'Int' to 'AtomicRepresentable' is only available in macOS 15.0 or newer
4:9: error: 'load(ordering:)' is only available in macOS 15.0 or newer
4:25: error: 'relaxed' is only available in macOS 15.0 or newer

연산이 @_alwaysEmitIntoClient @_transparent 라서 명령은 실행 파일에 직접 들어가지만, 타입과 conformance 가 macOS 15 라서 그 이전 OS 로 back-deploy 되지는 않는다.


짧게 본 것들

락 없는 스택

제안서의 LockFreeSingleConsumerStack 을 그대로 두고 여러 스레드에서 push 했다. concurrentPerform 에서 stack 을 잡으면 warning 이 난다(StackNoUnsafe.swift).

1
69:31: warning: capture of 'stack' with non-Sendable type 'LockFreeSingleConsumerStack<Int>' in a '@Sendable' closure [#SendableClosureCaptures]

이 클래스는 Atomic<NodePtr?> 를 품어서 Sendable 로 선언할 수 없다. Stack.swift 는 nonisolated(unsafe) let s = stack 으로 우회했다. 8 개 스레드가 10_000 개씩 넣고 하나씩 꺼냈고, 20 번 모두 80000 3199960000 true 가 나왔다(개수, 합, 합이 0 부터 79_999 까지의 합과 같은지).

actor 와 함께

제안서의 Updater 예제의 빈 곳을 채워 돌렸다(Updater.swift). 출력은 0 1 0 이다. borrowing 으로 actor 에 넘긴 지역 atomic 이 await 뒤에도 같은 값을 보였다. actor 안의 nonisolated let reads = Atomic<Int>(0) 은 await 없이 바깥에서 읽고 쓴다(ActorNonisolated.swift). 두 번 read() 를 부른 뒤 출력은 reads 2 다.

unsafe 포인터

포인터를 담는 conformance 는 @unsafe 가 붙어 있다. UnsafeConf.swift 는 기본 설정에서 진단이 없고, -strict-memory-safety 에서 두 줄에 warning 이 나온다.

1
warning: expression uses unsafe constructs but is not marked with 'unsafe' [#StrictMemorySafety]

(생성 줄과 store 줄, 3:11 과 4:3)


스레드에서 오간 이야기

포럼 스레드는 시간 순서대로 따라갔다. 화자와 날짜는 스레드 원문에서 다시 확인한 것이다.


pitch 와 첫 리뷰

pitch 는 2023-09-18 부터 10-16 까지, 첫 리뷰는 10-23 부터 11-06 까지 열렸다. 질문은 이름, SIMD, 모듈 위치, 실행 비용으로 나뉜다.

SIMD 를 atomic 으로 쓸 수 있느냐는 질문이 첫날 나왔다(ajo, #2, 10-23). Alejandro 는 한 타입이 한 프로토콜을 한 번만 따를 수 있어서 어렵다고 답했다(#3). scanon 은 SIMD 를 struct 로 감싸고 AtomicRepresentation 을 UInt64 로 두라고 제안했다(#5). 10-31 에 Joe_Groff 가 AtomicSIMDNWrappable 같은 프로토콜이 가능하다고 했지만 SIMD 는 이번 제안에서 빠졌다.

grynspan 은 compareExchange 대신 compareAndExchange 같은 이름을 원했다(#4, 10-23). 앞에서 본 것처럼 lorentey 는 C++11 용어를 따른 것이라고 했고, 전문가들이 튜플 반환을 선호한다는 말도 덧붙였다(#13, 10-26).

pyrtsa 는 WordPair 에 Equatable, Hashable, Comparable, Sendable 을 달라고 했다(#9, 10-25). Alejandro 가 이를 PR 로 넣으면서 highWord/lowWord 를 first/second 로 바꿨다고 알렸다(#20, 10-30).

Atomic 을 기본 namespace 에 두지 말자는 말도 나왔다(lorentey, #11, 10-26). 이것이 모듈 분리의 씨앗이 됐다. 같은 날 nonsensery 는 AtomicRepresentable 과 AtomicOptionalRepresentable 이라는 이름을 처음 냈다(#17). 이것이 수락 때의 최종 이름이 된다.

wrappingAdd 의 이름은 xwu 와 scanon 이 이야기했다(#25, #26, 10-31). scanon 은 “overflow add” 는 넘치지 않으니 나쁜 이름이라고 했다.

락 없는 반복문에서 spin 이나 양보를 넣어야 하느냐는 질문도 나왔다. John_McCall 은 compare-exchange 반복문에서는 물러서는 시간이 의미가 없고 불공정은 감수하는 거래라고 했다(#47, 11-03). David_Smith 는 spinlock 과 priority inversion 을 들어 OSAllocatedUnfairLock 을 대안으로 말했다(#51, 11-04).

가장 길게 논쟁이 이어진 것은 let 과 var 였다. 10-31 에 John_McCall 은 프로그래머가 atomic 을 자연스럽게 var 로 선언할 텐데 그것이 언제나 틀리고 진단도 없다고 말했다(#29). var 를 막거나 let 으로 읽는 attribute 를 넣고 mutating 도 막자고 했다. generics 를 거치면 가변인 atomic 이 생길 수 있지만 드물 테니 99% 를 덮으면 된다는 것이었다. 11-01 에 Joe_Groff 는 let 과 var 가 실은 shared 와 exclusive 의 구분이라고 했고, 진단은 동적 exclusivity 검사를 받는 var(class 프로퍼티, escape 하는 closure 캡처, 전역과 static)에만 걸자고 했다(#31). Douglas_Gregor 는 이것을 어떻게 가르칠지 생각하고 있다고 했다(#32). Alejandro 는 이에 반대로 동적 검사가 있든 없든 var 는 모두 막자고 했다(#34, 11-01). 지역 var x = Atomic<Int>(0) 에 x = Atomic<Int>(123) 을 쓰면 atomic 연산이 아닌 대입이 되기 때문이다. John_McCall 은 별도 제안으로 미루지 말고 이 제안에서 정하자고 답했다(#35, 11-02).


수정 요청

11-17 에 Joe_Groff 가 수정을 요청했다(#53). 리뷰는 10-23 부터 11-06 까지였다. 요청은 셋이다.

  1. 동적 exclusivity 검사가 필요한 var(class 인스턴스 프로퍼티, 전역, escape 한 지역)로 Atomic 을 쓰면 진단한다. 우선 Atomic 에만 적용한다.
  2. API 를 명시적으로 import 하는 별도 모듈로 옮긴다. 시작 이름으로 Atomics 를 제안했다.
  3. AtomicValue 와 AtomicOptionalWrappable 이름을 맞춘다. 예로 AtomicWrappable 과 Atomic<Wrapped> 를 들었다.

그대로 받아들인 것도 있다. SIMD 는 conform 하지 않고, atomicMemoryFence(ordering: .relaxed) 는 no-op 이라도 허용하고, C/C++ atomics interop 은 나중으로 두고, ordering view 는 조합이 너무 늘어나서 기각했다.


두 번째 리뷰

12-04 부터 시작했다. Joe_Groff 가 바뀐 점을 요약했다(#1). 모듈 이름은 Atomics 대신 Synchronization 으로 했다. 다른 동기화 API 도 둘 자리가 필요하고 swift-atomics 의 Atomics 와 충돌을 피하려는 것이었다. AtomicValue 라는 이름은 swift-atomics 에서 옮기는 마찰을 줄이려고 유지했다.

let 인데 값이 바뀐다는 점이 헷갈린다는 반론이 12-04 부터 05 일까지 이어졌다. Joe_Groff 는 immutable 이 shared access 의 특수한 경우라고 했고(#7), let 은 어느 container 를 가리키는지를 못 바꾸는 것이라고 했다(#23). jrose 는 heap 포인터를 품은 struct 와 같다고 보자고 했다(#28, 12-05). pyrtsa 는 Atomic 을 품은 struct 를 var 로 두는 것도 막느냐고 물었고(#29, 12-05), 앞의 측정이 그 답이다. 6.4 는 막지 않는다. Joe_Groff 는 Rust 가 같은 모델을 10 년 가까이 썼다고 했다(#40, #53). Rust 의 & 와 &mut 가 shared 와 exclusive 에 대응한다.

lorentey 와 John_McCall 은 atomic 이 다른 종류의 타입이라고 봤고, mutating 으로 만드는 것은 나쁘다고 했다(#61, #62, 12-06).

이름도 다시 나왔다. bbrk24 는 DoubleWord 가 Windows 에서 32 비트로 읽힌다고 했고(#63), scanon 은 Swift 에서 “Word” 가 포인터 크기이고 WordPair 가 값 두 개를 묶는다는 점에서 더 맞다고 했다(#64, 12-06). 12-14 에 Joe_Groff 는 모듈 이름, AtomicValue, WordPair 에 대한 의견을 다시 구했다(#98). swift-atomics 와의 호환과 더 좋은 이름이 부딪힌다고 짚었다. ksluder 는 AtomicWrappable 이 마음에 들지 않는다고 했고(#100), wes1 은 서로 다른 이름을 원했다(#101). wadetregaskis 가 12-15 에 “이전은 재미있지만 표준 라이브러리는 영원하다” 는 뜻으로 말해서 이름이 이력보다 좋아야 한다는 쪽으로 기울었다(#102).

Sendable 이 조건부인 이유도 길게 다뤘다. Karl 이 물었고(#72, 12-07), Joe_Groff 는 non-Sendable 포인터를 스레드 사이로 옮기는 통로가 된다고 답했다(#73). lorentey 는 조건부 Sendable 을 단순한 경우를 위한 편의 기능이라고 봤다(#74). 12-13 에 Joe_Groff 가 Atomic 을 Sendable 로 두지 말자는 생각이 나왔다고 전했고(#79), lorentey 도 빼는 쪽이 낫다고 썼다가 나중에 스스로 거둬들였다(#80). 그러나 jrose 는 두 Task 에 atomic 을 잡을 수 없게 된다고 반대했고(#81, 12-13), John_McCall 도 반대했다(#84). 포인터를 품은 atomic 과 Rust 의 AtomicPtr 가 도마에 올랐다(#86, #87, #91, #93, 12-13). Rust 의 AtomicPtr 는 무조건 Send 인데 John_McCall 은 그것을 구멍으로 받아들인 것으로 읽었고(#93), Gankra 는 꺼낸 포인터를 쓰는 연산이 여전히 unsafe 를 요구하니 구멍이 아니라고 반박했다(#94). Joe_Groff 는 12-20 에 1월 2일까지 연장하면서 Atomic<Unsafe*Pointer> 의 Sendable, AtomicValue 이름, 모듈 이름을 다시 물었다(#107). lorentey 는 같은 날 Atomic 을 non-Sendable 로 두면 잡일만 늘 뿐이라는 #107 의 전제에 강하게 반대하면서, @unchecked Sendable 을 적는 일은 군더더기가 아니라고 했다(#108). 1월 2일에 Alejandro 는 AtomicRepresentable 이 괜찮은 이름이라는 다른 리뷰어들의 말에 동의했다(#129).


수락

2024-01-03 에 Joe_Groff 가 accepted with modifications 로 알렸다. 고친 것은 이름 둘이다. AtomicValue 는 AtomicRepresentable 로, AtomicOptionalWrappable 은 AtomicOptionalRepresentable 로 바뀌었다. 그대로 둔 것은 Atomic 이라는 이름, Synchronization 이라는 모듈 이름, WordPair 라는 이름이다. immutable 대 mutable 이 실은 shared 대 exclusive 라는 소유권 모델도 Rust 선례를 들어 그대로 두었고 var 진단도 그대로다. Sendable 은 Value 에 따라 조건부로 남겼다. Atomic<UnsafePointer<T>> 구멍이 걱정되는 자리다.


뒷이야기

수락 공지 아래에 2025 년에 글이 더 붙었다. benrimmington 이 6.0 에 WordPair 의 Comparable 이 빠져 있다고 알렸다(#4, 2025-01-23). Alejandro 가 같은 날 swiftlang/swift#78857 로 더 높은 availability 를 달아 고쳤다고 답했고(#5), John_McCall 은 2025-02-03 에 LSG 가 재리뷰 없이 넣기로 했다며 release note 를 요청했다(#6). 앞의 WordPairCmp.swift 의 15.4 가 그 결과다.


기대 효과

  • 락을 잡지 않고 숫자 하나, 상태 하나, 포인터 하나를 여러 스레드에서 읽고 바꿀 수 있다.
  • 컴파일러가 연산을 인라인해서 ldadd 나 casp 같은 CPU 명령이 호출하는 쪽에 직접 들어간다.
  • var 로 잘못 선언하는 일을 컴파일러가 막아 준다.
  • 메모리 순서를 연산마다 적게 해서 어떤 보장을 기대하는지가 코드에 남는다.
  • Task, actor, Dispatch 어디서든 지역 let 이나 필드로 같은 방식으로 쓸 수 있다.

다른 선택지는 왜 안 됐나

제안서의 Alternatives 에서 고른 것만 적는다.

  • 기본 메모리 순서를 두는 안. 순서를 매번 적게 해서 코드를 읽는 사람이 보장을 알 수 있게 했다. 기본값이 필요하면 앞의 DynOrdering4.swift 처럼 직접 overload 를 만든다.
  • 보편 Atomic<T>. 모든 T 에 Atomic 을 허용하지 않고 AtomicRepresentable 을 따르는 타입으로 한정했다.
  • value 프로퍼티. counter.value += 1 은 읽고 쓰는 두 단계라서 경합이 생긴다.
  • 순서를 메서드 이름에 넣는 안, 순서를 generic 인자로 받는 안, ordering view. 조합이 늘어나 표면이 커져서 버렸다.
  • DoubleWord 대신 WordPair. Windows 에서 DoubleWord 가 32 비트로 읽히기 때문이다.
  • 모듈 이름 Atomics 대신 Synchronization. 다른 동기화 API 도 같은 모듈에 둘 자리가 필요했고 swift-atomics 의 이름과 겹치지 않아야 했다.

앞으로의 방향으로 제안서는 atomic strong reference 와 메모리 회수를 남겨 두었다.


Swift 6 모드와 마이그레이션

소스와 ABI 모두 순수 추가라서 기존 코드는 영향을 받지 않는다. 위의 Counter.swift, Ops.swift, State.swift, WordPair.swift, Lazy.swift 는 Swift 6 모드(-swift-version 6)로 컴파일했고 진단이 없었다. Lazy.swift 의 var atomicLazyFoo 같은 computed property 는 Atomic 타입이 아니라 Foo 를 돌려주는 것이라 걸리지 않는다.

실제로 걸리는 것은 배포 대상이다. 타입과 conformance 가 macOS 15 라서 그 아래를 지원하는 앱은 if #available 로 갈라야 한다. swift-atomics 에서 옮기는 경우에는 모듈 이름이 Atomics 에서 Synchronization 으로, 프로토콜 이름이 AtomicValue 에서 AtomicRepresentable 로 바뀌었다는 점과 var 로 선언한 곳이 error 가 된다는 점을 고쳐야 한다.


정리

항목내용
모듈import Synchronization 이 있어야 Atomic 이 보인다
모양~Copyable, @_rawLayout, 연산은 @_transparent 라서 ldadd, casp 가 직접 들어간다
선언let 만 가능. var, 전역, 필드, computed, inout, mutating 은 error
남는 길Atomic 을 let 으로 가진 struct 를 var 로 두면 막지 않고 begin_access [read] [dynamic] 이 붙는다
ordering호출하는 자리에 .relaxed 같은 static 멤버를 직접 쓴다
add넘치면 CAS 앞의 덧셈에서 trap 하고 저장하지 않는다. wrappingAdd 는 감긴다
WordPair128 비트 casp. Comparable 은 macOS 15.4
AtomicLazyReferenceinit() 만. 여러 스레드가 만들어도 하나만 남는다
SendableValue 가 Sendable 일 때만. 포인터를 품은 Atomic 은 아니다
availabilitymacOS 15 부터. back-deploy 불가
  • 리뷰는 두 번 열렸다. 모듈 이름, 프로토콜 이름, var 진단이 첫 리뷰의 수정 요청이었고 두 번째 리뷰는 이름과 Sendable 조건을 다시 다뤘다.
  • AtomicValue 는 AtomicRepresentable 로, AtomicOptionalWrappable 은 AtomicOptionalRepresentable 로 바뀌었다.

관련 글


참고자료

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