
👋 들어가기 전
첫 번째로 학습할 attribute는 바로 @MainActor이다.
🏁 학습할 내용
- MainActor란
- @MainActor란
✅ MainActor란
actor 관련 내요은 https://hamp.tistory.com/212 를 먼저 보고 오는 것을 추천한다.
이제 우리는 Actor의 역할이 무엇인지 간단하게 살펴봤다.
이제는 MainActor를 알아보자.
iOS를 하며 Main이라는 접두사를 보면 가장 먼저 떠오르는 것은 바로 메인 쓰레드이다.
여기서도 마찬가지의 의미를 가진다.
메인 쓰레드는 프론트엔드 개발에서 UI/UX와 가장 맞닿아 있는 쓰레드이다.
❓ MainActor가 없었을 때
컨커런시 이전에 스레드 관련 내용은 GCD를 이용하거나, OperationQueue를 활용했다.
특히 mainThread를 이용하기 위해서는 아래와 같이 썼다.
DispatchQueue.main.async {
//code
}
여기서 중요한점은 공식문서에서도 이처럼 설명이되어있다.
A singleton actor whose executor is equivalent to the main dispatch queue.
정리하면 main dispatch queue를 완전히 대치할 수 있는 역할이라는 것
💧@MainActor란
✨ 역할
특이하게 @MainActor attribute는 2가지 역할이 존재한다.
- 컴파일 타임에서 Main Actor 검사 기능
- 컨커런시 검사기능은 컴파일 타임에 이뤄짐
- 컴파일 타임에 Main Actor context에서 실행된다고 선언함
- 즉, 런타임에는 MainActor에는 다른 context에서 동작할 가능성이 존재한다.
- isolation scope 제한
- 클로저 실행을 MainActor의 excutor에게 넘긴다.
⚠️ 주의할 점
Actor 특징 상, Actor 내의 state를 접근할 때, 언제 스레드가 할당 될 지 알 수 없어,
potential suspension point를 표시하기위해 await 키워드를 명시해야한다.
⌨️ 사용 예시
1. 컴파일 타임 Main Actor 검사기능

2. isolation scope 제한

😀 소감 및 마무리
아는 지인분께서 Concurrency를 정말 잘하셔서 도움을 정말 많이 주시고 계신다.
이번 기회에 Concurrency에 흥미를 붙혀, 주변에서 도움이 필요하면 나도 도와주는 사림이 되자!

출처
https://developer.apple.com/documentation/swift/mainactor
MainActor | Apple Developer Documentation
A singleton actor whose executor is equivalent to the main dispatch queue.
developer.apple.com
https://developer.apple.com/kr/videos/play/wwdc2021/10133/
Protect mutable state with Swift actors - WWDC21 - 비디오 - Apple Developer
Data races occur when two separate threads concurrently access the same mutable state. They are trivial to construct, but are notoriously...
developer.apple.com
'iOS > Swift Concurrency' 카테고리의 다른 글
| @unchecked Sendable (0) | 2025.05.12 |
|---|---|
| @Sendable (0) | 2025.05.11 |
| Actor (0) | 2025.05.08 |
| 컨커런시 문법 정리 (0) | 2025.03.22 |
| @TaskLocal (1) | 2025.03.22 |