Coroutine with Kotlin

Darby·2024년 2월 12일
post-thumbnail

코루틴에 대해 공부한 내용을 적은 글입니다. 틀린 부분이 있을 수도 있습니다.

Coroutine이 뭘까?

Coroutine에 대해 알기전에 routine이 뭔지를 알면 좋습니다.

routine이란?

컴퓨터 프로그램의 일부로서, 특정한 일을 실행하기 위한 일련의 명령.

위키피디아에 등재된 내용입니다.

한마디로 루틴은 어떠한 일을 하기 위한 프로그램?? 정도로 이해하고 넘어가면 좋을 것 같습니다.

그리고 코루틴을 사용하기 전에는 우리는 서브루틴이라는 방식으로 개발을 하였습니다.

fun routine() {
    routine1()
    routine2()
}

fun routine1(){
    print("Hello")
}

fun routine2(){
    print("안녕하세요")
}

routine 함수는 routine1의 "Hello"를 print하고 다시 메인 루틴이 호출한 장소로 돌아와 다음 루틴인 routine2 "안녕하세요"를 print하고 다시 메인 루틴이 호출한 장소로 돌아와 다음 루틴을 실행한다.

그러면 Coroutine은 무엇일까?

Coroutine은 일시 중단과 재개가 가능한 루틴이며 특정 Thread에 결합되어 있지 않으며 하나의 Thread에서 중단하고 다른 Thread에서 재개가 가능합니다.

출처 : https://gist.github.com/chaxiu/d87870528bbfe3e9d7e481e1f6acace1

위와 같이 Main Thread는 log를 찍어주고 네트워킹 작업같이 오래걸리는 작업은 IO Thread가 하고 있다.

중단(suspend) 어떻게 작동할까 ?
해당영상을 간략히 요약하면
suspension point라는게 있는데 이것은 게임의 check-point의 기능과 비슷합니다.
suspended 상태에서는 어떠한 자원도 사용하지 않음(Coroutine이 효율적인 이유)

기존의 Thread에서는 block을 걸면 자원을 사용하지 못하게 점유를 하고 있지만 Coroutine은 그렇지 않다. 또한 서로 다른 Thread에서 suspend와 resume이 가능하다.

suspent funtion이라고 모두가 중단 가능한 함수는 아니다.

CoroutineContext

코루틴이 실행될 때 실행 환경을 정의하고 구성합니다. (CoroutineContext = Coroutine 실행환경)

  • Job, CoroutineName, CoroutineDisPatcher, CoroutineExceptionHandler 등이 있다.
  • 모든 CoroutineScope와 Suspend function을 가지고 있음
  • CoroutineContext가 포함하는 모든 element는 unique key를 가진다. (중복허용 X)

모든 suspend function에서는 CoroutineContext에 접근이 가능하다.

  1. suspend function은 컴파일 시 Continuation을 파라미터로 추가해줍니다.
  2. Continuation은 CoroutineContext를 가집니다.
  3. 모든 suspend function은 current coroutine의 Context에 접근이 가능합니다.

CoroutineScope

  • child는 parent를 상속합니다.
  • parent는 모든 children이 끝날 때 까지 기다립니다.
  • parent가 취소되면, children도 취소됩니다.
  • child에서 에러가 발생하면 parent에게도 전파가 됩니다.
  • launch(), async()는 CoroutineScope의 확장 함수입니다.
  • runBlocking()은 오직 root coroutione으로 사용이 됩니다. (CoroutineScope의 확장 함수 X)

CoroutineScope도 CoroutineContext를 가지고 있습니다.

public interface CoroutineScope {
    /**
     * The context of this scope.
     * Context is encapsulated by the scope and used for implementation of coroutine builders that are extensions on the scope.
     * Accessing this property in general code is not recommended for any purposes except accessing the [Job] instance for advanced usages.
     *
     * By convention, should contain an instance of a [job][Job] to enforce structured concurrency.
     */
    public val coroutineContext: CoroutineContext
}





다음에는 Android에서는 어떻게 사용이 되고 있는지 알아보겠습니다.

드로이드나이츠에 있는 영상을 정리한 글인데요. 다른 영상은 안보셔도 Android 개발을 하신다면 한 번쯤 보시는걸 추천드립니다.

감사합니다.


참고자료

https://www.youtube.com/watch?v=x0KY6qtuNHg&ab_channel=DroidKnights
https://gist.github.com/chaxiu/d87870528bbfe3e9d7e481e1f6acace1
https://dev.gmarket.com/82
https://developer.android.com/kotlin/coroutines?hl=ko
https://www.youtube.com/watch?v=eJF60hcz3EU&ab_channel=%EB%8B%B9%EA%B7%BC%ED%85%8C%ED%81%AC

profile
성장하는 개발자가 되자

0개의 댓글