scope Builder 를 통해서 알아야할 것 : 동시성 프로그래밍을 하기위해서 사용되는 scope Builder. 기본 키워드(launch, async, runBlocking) 도 scopeBuilder 를 통해서 coroutine Scope 이 설정되어있고, 커스터마이징도 가능하다.
또한 runBlocking 블록과 coroutineScope 블록의 차이점도 가져갈 수 있다.
coroutine 을 통해서 제공되는 coroutineScope 은 coroutineContext를 상속받으면서 Coroutine의 생명주기를 관리해준다.
coroutineScope builder 키워드를 통해서 스콥을 선언해서 사용할수있다. 이것은 코루틴 스콥을 만들고 런치된 자식스콥이 완료될때까지 완료되지 않는다.
runBlocking 키워드 역시 새로운 코루틴을 실행하고 완료될때까지 현재의 쓰레드를 블로킹하는데, 메인함수에서 메인 쓰레드가 종료되지 않기위해 runBlocking 키워드를 통해서 메인 함수 자체를 코루틴으로 실행할수 있다.
즉 코드로 확인해보면,
fun main() = runBlocking {//main 함수 자체를 코루틴 환경에서 실행 launch { //그 중에서도 백그라운드로 코루틴 실행 delay(1000L) //코루틴을 기다리게함 println("런블로킹 내에 런치 블록") } println("런치 블록 밖") }
<결과> 런블로킹 내에 런치 블록 런치 블록 밖
이 코드는 coroutineScope 키워드를 사용해서 아래와 같이 바꾸어서 사용할 수 있다.
suspend fun main() = coroutineScope {//main 함수 자체를 코루틴 환경에서 실행 launch { //그 중에서도 백그라운드로 코루틴 실행 delay(1000L) //코루틴을 기다리게함 println("런블로킹 내에 런치 블록") } println("런치 블록 밖") }
그러면, runBlocking 키워드와 coroutineScope 키워드는 뭐가 다른가.
runBlocking 블록은 현재 쓰래드를 대기시킨다.
coroutineScope 은 뒷단의 쓰레드를 다르게 사용할 수 있도록 해제(release) 시키고 대기한다(suspend).
이러한 차이때문에 runBlocking 은 일반적인 함수이고, coroutineScope 은 suspended 키워드를 가진 함수이다.
(–> runBlocking 키워드는 main 함수 내에서나, 일반 global thread 에서도 사용할수있지만 coroutineScope은 이미 정의되어있는 동시 쓰레드 프로그래밍(runBlocking, launch, async 등으로 감싸져있는 블록들) 내에서 새로운 스콥을 정의해서 사용할 수 있다.
import kotlinx.coroutines.*
fun main() = runBlocking { // this: CoroutineScope
launch {
delay(200L)
println("런블로킹 블록을 실행한다.")
}
coroutineScope { // Creates a coroutine scope
launch {
delay(500L)
println("Task from nested launch")
}
delay(100L)
println("Task from coroutine scope") // This line will be printed
before the nested launch
}
println("Coroutine scope is over") // This line is not printed until the nested launch completes
}
fun main() {
GlobalScope.launch { // 1
println("Coroutine Running") // 2
delay(5000) // 4
}
println("test") // 3
}
// test
// main() 종료
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
fun main() = runBlocking {
launch {
println("Coroutine Running")
delay(5000)
}
println("test")
}
// test
// Coroutine Running
// 5초 뒤 main() 종료