Actor 뭘까

조영민·2022년 6월 12일
0

WWDC 2022를 보다가 Actor가 너무 많이 나왔다. Actor가 뭔지 모르니까 하나도 이해가 안간다.
뭔지 모르겠다. 공부해보자

Actor는 타입이다. class , struct 같이 인스턴스를 생성할 수 있고 프로퍼티, 메서드를 타입 내부에 선언할 수 있다.
protocol을 채택 가능하며 extension 역시 가능하다.
참조타입이다.

아니 근디 왜 쓸까?

Actor는 data race를 방지해준다.

class FruitStorage { 
	var bananaCount: Int = 10 
}
let julyStorage = FruitStorage()

요런게 있다고 치면
JulyStorage의 bananaCount를 다른 스레드에서 같이 쓰면 datarace가 발생한다.

Like classes, actors are reference types, so the comparison of value types and reference types in Classes Are Reference Types applies to actors as well as classes. Unlike classes, actors allow only one task to access their mutable state at a time, which makes it safe for code in multiple tasks to interact with the same instance of an actor

출처: https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html

위의 블럭을 보면 참조 타입이라는 설명과 함께 변화하는 상태를 한번에 하나씩만 허락한다고 적혀있다.

actor TemperatureLogger {
    let label: String
    var measurements: [Int]
    private(set) var max: Int

    init(label: String, measurement: Int) {
        self.label = label
        self.measurements = [measurement]
        self.max = measurement
    }
}

You introduce an actor with the actor keyword, followed by its definition in a pair of braces. The TemperatureLogger actor has properties that other code outside the actor can access, and restricts the max property so only code inside the actor can update the maximum value.

프로퍼티를 외부에서 접근 불가능하다고 적혀있다.
오호 .. private이 아닌디 신기하다.

You create an instance of an actor using the same initializer syntax as structures and classes. When you access a property or method of an actor, you use await to mark the potential suspension point.

await 랑 함께 쓰란다..
async await도 포스팅해야된다는 사실이 너무 슬프다.

actor를 쓰는 이유는 변할 수 있는 값을 변경하려는 동작이 여러 스레드에서 일어나서 data race가 일어나는걸 방지하기 위함이다. 그럼 let은 ?
변하지 않는 값이니 외부에서 접근이 가능한가 ?
그렇다.

또한 비동기함수로 호출하면 접근이 가능하다.
async await을 쓰면 된다는 소리구나 .. 아니면 탈출 클로저도 가능한가 ? 이건 추후에 알아보자
진짜 모르겠다.

자 그러면 var 면 외부에서 접근 불가고 비동기가 아니면 접근도 불가해?
그럼 이걸 왜써 너무 불편해
라고 할 수 있겠다.

출처: https://github.com/apple/swift-evolution/blob/main/proposals/0313-actor-isolation-control.md

func deposit(amount: Double, to account: isolated BankAccount) {
  assert(amount >= 0)
  account.balance = account.balance + amount
}

신기한게 있다.

actor BankAccount {
  nonisolated let accountNumber: Int
  var balance: Double

  // ...
}

더 신기한것도 있다.
나중에 알아보자 다음글에서 봐요 ..

세줄요약 :
1. class랑 비슷 상속 불가
2. 외부에서 참조 불가( 이래서 data safe한듯 )
3. 가끔 가능 (알아볼예정 )

0개의 댓글