-
[Swift] ThreadSafe 한 Class 만들기Swift 2023. 10. 24. 13:26
Actor | Apple Developer Documentation
Common protocol to which all actors conform.
developer.apple.com
Sendable | Apple Developer Documentation
A type whose values can safely be passed across concurrency domains by copying.
developer.apple.com
동시에 여러 쓰레드에서 하나의 인스턴스에 접근하면 어떻게 될까?
아무 조치도 취하지 않는다면 값은 이미 변했지만 변하지 않은 값을 돌려받을 수도 있다.
그래서 thread safe 하게 race condition 을 피해주어야한다.
그럴때 사용되는 것이 Actor 와 Sendable 이다 Actor 는 Sendable 이라는 protocol 을 채택하고 있다.
Sendable 을 채택하는 자원에 접근할때는 await 로 접근해야한다. 왜냐하면 자원에 접근하는 순서가 보장되어
race condition 을 피하기 때문이다. 만약 Sendable 을 사용하기 어렵거나 Sendable 없이 구현하려면 어떻게 해야할까?
정답은 큐를 직접 만들어 해당 큐를 통해서 값에 접근하면된다 아래와 같이!
class ThreadSafeClass { private var name: String private var age: Int private let queue = DispatchQueue(label: "com.kim.ThreadSafeClass") init(name: String, age: Int) { self.name = name self.age = age } func update(name: String) { queue.async { self.name = name } } func update(age: Int) { queue.async { self.age = age } } }
'Swift' 카테고리의 다른 글
[Swift] NSPredicate format placeholders (0) 2023.10.25 [Combine] AsyncPublisher 란? (0) 2023.10.24 [Swift] DispatchQueue.global() 과 Task.detatched(priority: .background) 의 차이점 (0) 2023.10.24 [Swift] Mirror 써보기 (0) 2023.10.18 [Swift, Combine] AnyPublisher 를 async/await throws 로 사용해보자 (0) 2023.10.04