[Kotlin] Coroutines dispatchers

머핀조아·2023년 3월 26일
2

Kotlin

목록 보기
2/2
post-thumbnail

Coroutines dispatchers

코루틴을 실행(시작 및 재개)할 스레드를 결정하는 도구

Coroutine을 어떻게 처리할 것인지에 대한 정보가 담겨있는 CoroutineContext 안에 Dispatcher가 존재한다.


Dispatchers.Default

Designed to run CPU-intensive operations

Dispatcher를 설정하지 않았을 경우에 기본적으로 선택된다. 코드가 실행되는 컴퓨터의 코어 수와 동일한 크기(2개 이상)의 Thread pool이 있다. CPU 집약적인 계산을 수행한다고 가정한다면, 최적의 스레드 수이다. limitedParallelism function을 통해 동일한 스레드에서 실행되지만 특정 개수 이하로만 사용하도록 제한하는 dispatcher를 생성할 수 있다.

Dispatchers.Main

Designed to run operations in main thread

코드를 메인 스레드에서 실행할 수 있도록 한다. withContext가 호출되면 코루틴을 일시 중단하고 대기열에서 기다렸다가 다시 시작하게 되는데, Main thread에 있는 상태에서 withContext(Dispatchers.Main)를 호출하면 불필요하게 dispatch하는 비용이 발생한다. 이를 방지하기 위해 Main thread에서 호출되면 다시 dispatch 하지 않도록 하는 Dispatchers.Main.immediate를 withContext의 인수로 활용할 수 있다. 다른 dispatcher들은 즉시 dispatch를 지원하지 않는다.

Dispatchers.IO

Designed to run I/O operations

파일 입출력이 있거나, 네트워크 통신을 하는 등의 작업을 수행할 때 활용한다. Thread pool은 64개로 제한된다. Dispatchers.Default와 Dispatchers.IO는 같은 thread pool을 공유한다. 최적화를 위해 이와 같이 설계되었고, thread가 재사용되므로 redispatching이 필요하지 않은 경우가 많다. 예를 들어, Dispatchers.Default에서 실행하다가 withContext(Dispatchers.IO)를 수행할 경우, 대부분 동일 스레드를 유지하면서 Dispatchers.Default의 제한이 아니라 Dispatchers.IO 제한에 포함된다는 것이다. 하지만 제한은 서로 독립적이기 때문에 서로에 대한 간섭은 없다. 두 dispatcher를 최대로 사용한다고 하면, 64+8(core 개수)=72개의 활성 스레드를 가질 수 있다.

Dispatchers.IO에서 limitedParallelism function을 사용하면 thread 개수 제한이 없는, 독립적인 thread pool을 갖는 dispatcher를 생성할 수 있다.

Dispatchers.Unconfined

Designed to run operations regardless any context

실행중인 Thread를 변경하지 않는다. 시작되는 시점의 thread에서 시작되고, 재개되는 thread에서 재개된다는 특징이 있다. Thread 전환을 하지 않으므로 가장 저렴한 dispatcher이므로, 코드가 어떤 thread에서 실행되는지 전혀 신경쓰지 않는다면 활용할 수 있다.

CoroutineScope(Dispatchers.Unconfined).launch {
	println("Unconfined : Hello ${Thread.currentThread().name}")
	delay(500)
	println("Unconfined : World ${Thread.currentThread().name}")
}
runBlocking {
	println("Default : Hello ${Thread.currentThread().name}")
	delay(1000)
	println("Default : World ${Thread.currentThread().name}")
}
Unconfined : Hello main
Default : Hello main
Unconfined : World kotlinx.coroutines.DefaultExecutor
Default : World main
profile
채찍질이 필요한 개발자

0개의 댓글