@MainActor

2025. 5. 8. 21:10·iOS/Swift Concurrency
반응형

👋 들어가기 전

첫 번째로 학습할 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가지 역할이 존재한다.

 

  1. 컴파일 타임에서 Main Actor 검사 기능
    • 컨커런시 검사기능은 컴파일 타임에 이뤄짐
    • 컴파일 타임에 Main Actor context에서 실행된다고 선언함
    • 즉, 런타임에는 MainActor에는 다른 context에서 동작할 가능성이 존재한다.
  2. 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
'iOS/Swift Concurrency' 카테고리의 다른 글
  • @unchecked Sendable
  • @Sendable
  • Actor
  • 컨커런시 문법 정리
Hamp
Hamp
남들에게 보여주기 부끄러운 잡다한 글을 적어 나가는 자칭 기술 블로그입니다.
  • Hamp
    Hamp의 분리수거함
    Hamp
  • 전체
    오늘
    어제
    • 분류 전체보기 (335) N
      • CS (30)
        • 객체지향 (2)
        • Network (7)
        • OS (6)
        • 자료구조 (1)
        • LiveStreaming (3)
        • 이미지 (1)
        • 잡다한 질문 정리 (0)
        • Hardware (2)
        • 이론 (6)
        • 컴퓨터 그래픽스 (0)
      • Firebase (3)
      • Programing Langauge (41)
        • swift (34)
        • python (6)
        • Kotlin (1)
      • iOS (134)
        • UIKit (37)
        • Combine (1)
        • SwiftUI (34)
        • Framework (7)
        • Swift Concurrency (22)
        • Tuist (6)
        • Setting (11)
        • Modularization (1)
        • Instruments (6)
      • PS (59)
        • 프로그래머스 (24)
        • 백준 (13)
        • LeetCode (19)
        • 알고리즘 (3)
      • Git (18)
        • 명령어 (4)
        • 이론 (2)
        • hooks (1)
        • config (2)
        • action (7)
      • Shell Script (2)
      • Linux (6)
        • 명령어 (5)
      • Spring (21)
        • 어노테이션 (6)
        • 튜토리얼 (14)
      • CI-CD (4)
      • Android (0)
        • Jetpack Compose (0)
      • AI (17) N
        • 이론 (10)
        • MCP (1)
        • LangGraph (6) N
  • 블로그 메뉴

    • 홈
    • 태그
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    IOS
    boostcamp
    property
    Swift
    dispatch
    CS
    SwiftUI
    Tuist
    concurrency
    프로그래머스
    dp
    AVFoundation
    dfs
    Spring
    protocol
    투포인터
    백준
    GIT
    lifecycle
    UIKit
  • 최근 댓글

  • 최근 글

  • 반응형
  • hELLO· Designed By정상우.v4.10.0
Hamp
@MainActor
상단으로

티스토리툴바