Skip to content

Commit

Permalink
Add kotlin/coroutine
Browse files Browse the repository at this point in the history
  • Loading branch information
jongmin92 committed Jul 2, 2020
1 parent 99c23ed commit 9649fd7
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions kotlin/coroutine.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# 코루틴
코루틴의 개념을 이해하기 위해서는 스레드에 엮이면 안된다. 코루틴을 스레드가 아닌 새로운 개념으로 받아들여야한다.

## 동시성(concurrency)과 병행성(parallelism)
동시성(concurrency)과 병행성(parallelism)은 다르다.

![concurrency](/kotlin/image/coroutine/concurrency.png)
`동시성`이란 CPU가 마치 여러가지 일을 동시에 하는 것 처럼 느껴지도록 하기 위해서 여러 스레드를 시분할 하여 처리하는 것이다. 이때, CPU가 처리하기 위한 스레드를 계속해서 변경하는 것(Context Switching)은 많은 리소스가 필요한 작업이다.

한편 현대의 대부분 CPU는 여러개의 core를 갖고 있다. 하나의 core에서는 하나의 스레드가 처리될 수 있는데, 이때 여러개의 core에서 여러개의 스레드가 동시에 실행되는 것을 `병행성`이라고 부른다.

## 코루틴
![coroutine](/kotlin/image/coroutine/coroutine.png)
코루틴은 개념적으로 스레드와 비슷하다. `경량 스레드`(light-weight thread)라고도 불린다. 경량 스레드라고 불리기 때문에 스레드와 연관지어 생각하려고 하는데, 경량 스레드라고 불리는 이유는 목적이 스레드와 같은 반면 더 성능이 좋고 가볍기 때문에 붙여진 별명이다.

코루틴 관련 자료나 예졔에서는 대부분 코루틴을 여러개 생성해서 동시성 프로그래밍을 보여준다. 이 과정에서 기존의 코루틴에 대한 개념이 없는 사람은 쉽게 코루틴도 결국 스레드들이라고 생각할 수 있다. 그러나 코루틴은 어떤 스레드에도 종속적이지 않을 수 있다.

코루틴은 하나의 스레드에서 실행될 수 있다. **하나의 스레드에 코루틴이 여러개 존재할 수 있고, 실행중이던 하나의 코루틴이 suspend(멈춤)되면, 현재 스레드에서 resume(재개)할 다른 코루틴을 찾는다.** 다른 스레드에서 찾는 것이 아니라 같은 스레드에서 찾는 것이다. (물론, 다른 스레드에서 resume 할 수도 있다.) 그렇게 때문에 스레드를 변경할 필요가 없으므로 Context Switching이 필요하지 않다.

suspend, resume은 모두 개발자가 직접 제어할 수 있다. 여러 작업을 갖고 동시성 프로그래밍을 할 때 OS가 스레드 스케쥴러에 의해서 컨트롤 했던 방식과는 다르다.
Binary file added kotlin/image/coroutine/concurrency.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added kotlin/image/coroutine/coroutine.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 9649fd7

Please sign in to comment.