CoroutineContext는 실행 환경을 설명하는 정보의 집합임. 어떻게 동작할지, 어디에서 실행될지
어떤 속성들을 가질지 등에 대한 정보를 포함함.

Dispatchers와 Threads

import kotlinx.coroutines.*

fun main() = runBlocking<Unit> {
    launch { println("main runBlocking : ${Thread.currentThread().name}") }
    launch(Dispatchers.Unconfined) { println("Unconfined : ${Thread.currentThread().name}") }
    launch(Dispatchers.Default) { println("Default : ${Thread.currentThread().name}") }
    launch(newSingleThreadContext("MyOwnThread")) { println("newSingleThreadContext : ${Thread.currentThread().name}") }
}

// 실행결과
Unconfined            : I'm working in thread main
Default               : I'm working in thread DefaultDispatcher-worker-1
newSingleThreadContext: I'm working in thread MyOwnThread
main runBlocking      : I'm working in thread main

Coroutines와 Threads 디버깅 하기

로깅을 통해 디버깅 하기

import kotlinx.coroutines.*

fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")

fun main() = runBlocking<Unit> {
    val a = async {
        log("I'm computing a piece of the answer")
        6
    }
    val b = async {
        log("I'm computing another piece of the answer")
        7
    }
    log("The answer is ${a.await() * b.await()}")    
}

// 실행결과
[main @coroutine#2] I'm computing a piece of the answer
[main @coroutine#3] I'm computing another piece of the answer
[main @coroutine#1] The answer is 42