본문 바로가기

컴퓨터 언어/Kotlin

01. 코루틴이란 무엇인가?

코루틴이란 무엇인가?

코루틴을 흔히 코틀린 고유의 구성요소라고 생각하는 경우가 있는데, 사실 코루틴은 서브루틴을 일시정지하고 재개할 수 있는 구성요소를 말합니다.

서브루틴은 간단하게 코틀린과 자바에 메서드나 함수로 이해하면 됩니다.

또한, 코틀린뿐만 아니라 파이썬, 자바스크립트 등 다양한 언어에서 코루틴을 지원하고 있습니다.

 

코루틴의 사용처

안드로이드의 경우 메인스레드에서 UI를 관리합니다.

그런데, 만약 메인 스레드에서 네트워크 요청이나 데이터베이스 검색 등 시간이 오래 걸리는 작업을 실행하면 어떻게 될까요? 메인스레드는 다른 작업을 처리하지 못하고 사실상 멈춰있는 것처럼 보이게 됩니다.

이를 해결하기 위해서 필요한 것이 동시성 프로그래밍이고 이를 위해 사용 되는 것이 코루틴입니다.

 

코루틴과 스레드의 차이점

  • 코루틴은 비선점형(Non-preemptive Multitasking) 멀티태스킹이며 동시성(Concurrency)을 지원하지만, 병행성(Parallel)을 지원하지 않는다.(참고 : 동시성 vs 병행성)
  • 코루틴은 스레드 내에서 실행 된다.
  • 코루틴은 중단 가능(Suspendable)합니다. 하던 작업을 도중에 중단하고 나중에 멈췄던 곳에서 다시 실행할 수 있습니다.
  • 문맥(context) 전환이 가능하다. A스레드에서 동작하던 코루틴을 B스레드에서 실행할 수 있습니다.
  • 코루틴은 스레드에 비해서 굉장히 가벼워 경량스레드(Light weight Thread)라고도 불린다. 

 

 

출처 : 

 

https://proandroiddev.com/understanding-kotlin-coroutines-with-this-mental-model-e1205e3f9670

 

Understanding Kotlin Coroutines with this mental model

For the majority of developers, the concept of a coroutine is pretty unfamiliar, although the first ideas date back to the early sixties…

proandroiddev.com

https://www.quora.com/Is-multithreading-concurrent-or-parallel

 

Is multithreading concurrent or parallel?

Answer (1 of 4): I am presently handling 3 concurrent tasks: I'm answering this question, working on a program, and drinking coffee. There's only one of me, so I can only make progress on one thing at a time, but I have started them all independently, and

www.quora.com

https://youtu.be/ShNhJ3wMpvQ

 

728x90
반응형

'컴퓨터 언어 > Kotlin' 카테고리의 다른 글

05. 코루틴의 runBlocking  (0) 2022.07.05
04. 코루틴의 Context  (0) 2022.07.05
03. 코루틴 suspend 함수  (0) 2022.07.05
02. 코루틴 첫 시작  (0) 2022.07.04
코루틴 관련해서 좋은 블로그  (0) 2021.08.31