Coroutines basics

Minsuk Jang·2021년 10월 9일
0
post-thumbnail

코루틴 공식 문서

First coroutine

fun main() = runBlocking {
    launch {
        delay(1000L)
        println("World!")
    }

    println("Hello")
}

launch

1. 코루틴 Builder
2. 새로운 코루틴을 동시적으로 실행시킨다.
3. 작업이 독립적으로 수행된다.
4. CoroutineScope에서만 명시돼야 한다.

delay

1. 특정 시간 동안 코루틴을 중단시키는 역할

runBlocking

1. 코루틴 Builder
2. runBlocking 내부에 있는 모든 코루틴의 동작이 완료될 때까지 블록킹된다.

Structured concurrency

  • 새로운 코루틴은 코루틴 자신의 생명주기를 한정짓는 특정한 CoroutineScope 내에서 실행되어야 한다.
  • Structured concurrency는 많은 코루틴들이 잃어버리거나 메모리 누수되지 않도록 보장해준다.

명확하게 어떤 의미인지 살펴볼 필요성이 있음

Extract Function

suspend 키워드를 이용하여 delay를 사용할 수 있고 이를 통해 함수화 시킬 수 있다.

fun main() = runBlocking {
    launch {
        doWorld()
    }

    println("Hello")
}

//suspend 키워드가 없으면 delay를 사용할 수 없다
suspend fun doWorld(){ 
    delay(1000L)
    println("World!")
}

Scope Builder

runBlocking와 corountineScope 특징

공통점

  • 코루틴 빌더
  • Scope내에 있는 함수들이 모두 완료될 때까지 기다린다.

차이점

  • runBlocking는 대기를 위해 현재 스레드를 차단시킨다.
  • coroutineScope는 일시 중단되어 다른 용도를 위해 스레드를 해제시킨다.

무슨 말인지 차차 배워나아가면서 알아봐야겠다

Scope builder and concurrency

fun main() = runBlocking {
    doWorld()
    println("done")
}

suspend fun doWorld() = coroutineScope{
    launch {
        delay(2000L)
        println("World 2")
    }

    launch {
        delay(1000L)
        println("World 1")
    }
    println("Hello")
}

launch 블록들은 동시에 실행이 된다.

An explicit job

  • launch 코루틴 빌더는 Job 객체를 반환한다.
  • 반환된 Job 객체를 이용하여 명시적으로 launch or wait이 가능하다.
fun main() = runBlocking{
    val job = launch{
        delay(1000L)
        println("World!")
    }
    println("Hello")
    job.join() //자식 코루틴이 완료될때까지 기다린다.
    println("Done")

}

light-weight

fun main() = runBlocking{
    repeat(100_000){
        launch {
            delay(5000L)
            print(".")
        }
    }
}

코루틴은 경량하다. 10만개의 코루틴을 생성하여 점을 찍어도 out of memory 현상 없이 점이 찍히는 것을 확인할 수 있다.

profile
Positive Thinking

0개의 댓글