대표 사진!

 go를 공부하면서 가장 흥미로웠던 주제였던 goroutines에 대해서 알아 봅니다. 

https://golang.org/doc/effective_go.html

golang 사이트의 effective go에 게시된 goroutions에 대한 글을 먼저 번역합니다. 

Effective go의 goroutines 설명

https://jungwoong.tistory.com/66

 

[golang] Effective Go - Concurrency

goroutines과 channels를 공부하기 위해서 golang 사이트 effective go의 concurrency에 대한 부분을 살펴봅니다. https://golang.org/doc/effective_go.html#concurrency Effective Go - The Go Programming Lang..

jungwoong.tistory.com

Goroutine 사용하기

 go routine을 사용하면 os 스레드보다 훨씬 가볍게 비동기 동작을 수행합니다. 

// SleepPrint 은 시간을 전달받아 그시간만큼 지연시킨 다음에
// msg를 출력합니다.
func SleepPrint(duration time.Duration, msg string) {
    time.Sleep(duration)
    println(msg)
}

func main() {
    // goroutines 을 사용하지 않고 동기적으로 실행
    SleepPrint(time.Second*3, "first msg")
    SleepPrint(time.Second*2, "second msg")
    SleepPrint(time.Second*1, "three msg")

    time.Sleep(time.Second * 5)
    println("end msg")
}

결과 화면

 SleepPrint함수는 전달된 시간만큼 지연한후 msg를 출력하는 함수 입니다. 

 위의 예제는 goroutine을 사용하지 않고 동기적으로 수행하는 예제입니다.

 순차적으로 수행되는 것을 확인 할 수 있습니다.

func main() {
    // goroutines 을 사용하지 않고 동기적으로 실행
    go SleepPrint(time.Second*3, "first msg")
    go SleepPrint(time.Second*2, "second msg")
    go SleepPrint(time.Second*1, "three msg")

    time.Sleep(time.Second * 5)
    println("end msg")
}

결과 화면

 SleepPrint를 goroutines을 사용해서 호출하게 되면 비동기적으로 수행합니다. 

+ Recent posts