김호쭈
DevForYou
김호쭈
전체 방문자
오늘
어제
  • 분류 전체보기 (321)
    • • 데이터베이스(DB) (9)
      • __SQL__ (9)
    • •알고리즘(Algorithm ) (117)
      • 문제풀이 (99)
      • 스터디 (14)
      • 알고리즘 팁 (4)
    • •Compter Science (57)
      • Operating System (25)
      • Computer Network (1)
      • Computer Vision (16)
      • Artificial Intelligence (14)
      • Software Technology (1)
    • • 독서 (36)
      • Design Pattern (24)
      • 객체지향의 사실과 오해 (1)
      • Object Oriented Software En.. (11)
    • • 개발 (26)
      • React (3)
      • node.js (6)
      • Django (11)
      • Spring boot (6)
    • • 개발Tip (4)
      • GitHub (0)
    • •프로젝트 (2)
      • 물물 (2)
    • •App (54)
      • 안드로이드 with Kotlin (50)
      • 코틀린(Kotiln) (4)
    • •회고 (8)
    • •취준일기 (3)
    • • 기타 (2)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • ㄱ
  • local저장소
  • GitHubDesktop
  • KMU_WINK
  • 원격저장소
  • Remote저장소
  • 깃허브데스크탑
  • 로컬저장소

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
김호쭈

DevForYou

[코루틴#2] 코루틴 스코프(Coroutine Scope)와 잡(Job)을 이용한 join
•App/코틀린(Kotiln)

[코루틴#2] 코루틴 스코프(Coroutine Scope)와 잡(Job)을 이용한 join

2022. 8. 5. 04:03
 

[코루틴#1] 코루틴 시작하기, runBlocking, launch, delay, suspend

# 시작하며  앱공부를 하다보니까, 아키텍처와 코루틴의 중요성을 알게 됐다. 그래서 책도사고 여러가지 공부할 방법을 고심했는데, 결국 강의하나를 질렀다. 코루틴에 대해서 셜명해주는 강의

devforyou.tistory.com

 

# suspension point

해당 지점에서 코루틴이 잠들 수 있고, 깨어나는 지점이다. 쓰레드를 점유하지 않고 양보 할 수 있다.

delay와 suspend키워드로 작성한 함수는 suspension point가 된다.

잠시 잠들었다가 돌아 올 수 있는 지점이다. 

 

# launch

import kotlinx.coroutines.*

suspend fun doOneTwoThree() {
    launch {
        println("launch1: ${Thread.currentThread().name}")
        delay(1000L)
        println("3!")
    }

    launch {
        println("launch2: ${Thread.currentThread().name}")
        println("1!")
    }

    launch {
        println("launch3: ${Thread.currentThread().name}")
        delay(500L)
        println("2!")  
    }
    println("4!")
}

fun main() = runBlocking {
    doOneTwoThree()
    println("runBlocking: ${Thread.currentThread().name}")
    println("5!")
}

위 코드는 실행 되지 않는다.

 

그렇기 때문에 아래와 같이 코루틴스코프를 만들어준 후 그안에서 실행되어야 한다.

 

import kotlinx.coroutines.*

suspend fun doOneTwoThree() = coroutineScope {
    launch {
        println("launch1: ${Thread.currentThread().name}")
        delay(1000L) //suspension point
        println("3!")
    }

    launch {
        println("launch2: ${Thread.currentThread().name}")
        println("1!")
    }

    launch {
        println("launch3: ${Thread.currentThread().name}")
        delay(500L) //suspension point
        println("2!")  
    }
    println("4!")
}

fun main() = runBlocking {
    doOneTwoThree() //suspension point
    println("runBlocking: ${Thread.currentThread().name}")
    println("5!")
}

부모 코루틴안에 런치로 자식 코루틴을 생성한것이다. 부모는 항상 자식을 수용하기 때문에, 자식 코루틴이 모두 종료되면 부모 코루틴또한 종료된다. 

코루틴 스코프는 코루틴 빌더를 수행 할 수 있게 하기 위해서 존재한다.

launch는 반드시 코루틴 안에서 수행되어야 한다. doOneTwoThree()함수안의 launch는 suspend함수에서 실행되는 것일 뿐이지 코루틴 안에서 수행되는것이 아니다. 

runBlocking은 현재 쓰레드를 멈추게하고 기다린다. 그러나 코루틴 스코프는 현재 쓰레드를 멈추게 하지 않는다.

 

# job & join

import kotlinx.coroutines.*

suspend fun doOneTwoThree() = coroutineScope {
    val job = launch {
        println("launch1: ${Thread.currentThread().name}")
        delay(1000L)
        println("3!")
    }
    job.join()

    launch {
        println("launch2: ${Thread.currentThread().name}")
        println("1!")
    }

    launch {
        println("launch3: ${Thread.currentThread().name}")
        delay(500L)
        println("2!")  
    }
    println("4!")
    
}

fun main() = runBlocking {
    doOneTwoThree()
    println("runBlocking: ${Thread.currentThread().name}")
    println("5!")
}

코루틴 빌더 launch는 job객체를 반환한다. join은 해당 블록의 작업이 끝날때까지 기다리게 한다. 

launch1: main @coroutine#2
3!
4!
launch2: main @coroutine#3
1!
launch3: main @coroutine#4
2!
runBlocking: main @coroutine#1
5!

위의 결과를 반환한다. 

 

# 마치며

패스트캠퍼스 김용욱님의 코루틴 강의를 참고하여 작성했습니다.

저작자표시 (새창열림)

'•App > 코틀린(Kotiln)' 카테고리의 다른 글

[코루틴#1] 코루틴 시작하기, runBlocking, launch, delay, suspend  (0) 2022.08.04
[코틀린 문법] 코틀린에서 for문과 when문 사용방법, 코틀린 반복문  (0) 2022.03.12
[코틀린 문법] 코틀린에서 ? 와 !! 사용법 및 nullable에 대해서, nullsafe  (0) 2022.03.12
    '•App/코틀린(Kotiln)' 카테고리의 다른 글
    • [코루틴#1] 코루틴 시작하기, runBlocking, launch, delay, suspend
    • [코틀린 문법] 코틀린에서 for문과 when문 사용방법, 코틀린 반복문
    • [코틀린 문법] 코틀린에서 ? 와 !! 사용법 및 nullable에 대해서, nullsafe
    김호쭈
    김호쭈
    공부하고 정리하고 기록하기

    티스토리툴바