[yeseul] 시즌 2: Week14#61
Open
HongYeseul wants to merge 1 commit into
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Week / 스터디 주차
시즌2 - 14주차
Chapter / 공부한 챕터
2장: 코루틴에 대해서
Page / 공부한 페이지
2장: 코루틴에 대해서
안녕하세요 😄
이번 주차는 자율 독서 기간이어서, 평소 회사에서 사용 중인 코루틴에 대해 공부해보았습니다.
코루틴은 이전부터 이해가 부족하다고 느껴 따로 시간을 내어 학습해보고 싶던 주제였는데, 이번 기회에 짧게나마 정리해보았습니다.
아래는 제가 정리한 내용입니다.
코루틴에 대하여
아래는
코틀린을 기준으로 작성되었습니다.코루틴은 일반 함수와 많이 비교를 하는데, 다음과 같습니다.
fun키워드 사용suspend fun키워드 사용suspend함수 내에서 일시 중단 가능Thread또는Executor사용launch,async등) 사용으로 간단하게 비동기 처리suspend함수 안에서 사용됨Dispatchers.IO,Dispatchers.Main)로 손쉽게 제어try-catch사용try-catch가능하며 구조적 코루틴 덕분에 관리 용이fun doWork(): Stringsuspend fun doWork(): String예시 비교
일반 함수
코루틴 함수
코루틴이 일반 함수와 다른 점은 자신이 이전에 마지막으로 실행된 위치를 알 수 있다는 점입니다.
이는 마치 운영 체제가 스레드를 스케줄링 하는 것과 동일합니다. 또한 구현 방법도 본질적으로 스레드와 차이가 없습니다.
반드시 유의할 점은 코루틴 몇 개를 생성하든 관계없이 운영체제는 이를 알지 못한다는 것입니다. 코루틴은 온전히 사용자 상태 내에서 구현된 것이기 때문에 코루틴을 사용자 상태 스레드로 해석할 수 있다.(코루틴의 스케줄링 제어권은 개발자에게 있다는 의미입니다.)
다시 말해, 함수는 특별한 연결 시작 지점이 없이 동작하는 일종의 코루틴이라고 볼 수 있습니다.
코루틴은 어떻게 구현될까?
코틀린은 일시 중지되거나 다시 시작될 수 있으며, 일시 중지될 때의 상태 정보를 반드시 기록해야 합니다. 이를 기반으로 코루틴을 다시 시작하는 것입니다.
코루틴도 함수 실행 자체는 일반 함수와 동일하게 스택에서 이뤄지며, 중단(suspend)이 발생할 경우에만 그 시점의 실행 상태(위치, 변수 등)를 힙에 저장해 두고 사용하는 구조입니다.
저장하는 실행 상태의 종류에는 다음과 같은 것들이 있습니다.
코루틴의 실행 흐름과 메모리(스택/힙) 사용 구조는 다음과 같습니다.
suspend) 도달Continuation)왜 코루틴이 중요할까?
코루틴의 중요한 역할 중 하나는 바로 프로그래머가 동기 방식으로 비동기 프로그래밍을 가능하게 한다는 것입니다.
이 부분이 더 궁금하다면 컴퓨터 밑바닥의 비밀 2.8절을 따로 참고해 보세요!