Go Routine

Reference: Go by example, A Tour of Go, ์˜ˆ์ œ๋กœ ๋ฐฐ์šฐ๋Š” Go ํ”„๋กœ๊ทธ๋ž˜๋ฐ

What is Go routines?

  • Go runtime์ด ๊ด€๋ฆฌํ•˜๋Š” Lightweight thread

  • Go์—์„œ "go" keyword๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด, runtime ์‹œ ์ƒˆ๋กœ์šด goroutine ์„ ์‹คํ–‰ํ•œ๋‹ค

  • goroutine์€ ๋น„๋™๊ธฐ์ (asynchronously) ์œผ๋กœ ํ•จ์ˆ˜ routine์„ ์‹คํ–‰ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์—ฌ๋Ÿฌ code๋ฅผ ๋™์‹œ์— (concurrently) ์‹คํ–‰ํ•˜๋Š”๋ฐ ์‚ฌ์šฉ๋œ๋‹ค

Why Go routine?

  • OS Thread ๋ณด๋‹ค ํ›จ์”ฌ ๊ฐ€๋ณ๊ฒŒ ๋น„๋™๊ธฐ concurrent ์ฒ˜๋ฆฌ๋ฅผ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•˜์—ฌ ๋งŒ๋“  ๊ฒƒ์œผ๋กœ, ๊ธฐ๋ณธ์ ์œผ๋กœ Go runtime์ด ์ž์ฒด ๊ด€๋ฆฌํ•œ๋‹ค

    • Go runtime ์ƒ์—์„œ ๊ด€๋ฆฌ๋˜๋Š” ์ž‘์—… ๋‹จ์œ„์ธ ์—ฌ๋Ÿฌ goroutine ๋“ค์€ ํ•˜๋‚˜์˜ OS Thread๋กœ ์‹คํ–‰๋œ๋‹ค

      • ์ฆ‰, goroutine๋“ค์€ OS Thrad์™€ 1:1๋กœ ๋Œ€์‘๋˜์ง€ ์•Š๊ณ , multiplexing์œผ๋กœ ํ›จ์”ฌ ์ ์€ OS Thread๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค

      • Memory ์ธก๋ฉด์—์„œ๋„ OS Thread๊ฐ€ 1MB์˜ stack์„ ๊ฐ–๋Š” ๋ฐ˜๋ฉด, goroutine์€ ์ด๋ณด๋‹ค ํ›จ์”ฌ ์ž‘์€ ๋ช‡ KB์˜ stack์„ ๊ฐ–๋Š”๋‹ค

    • Go runtime์€ goroutine์„ ๊ด€๋ฆฌํ•˜๋ฉด์„œ Go channel์„ ํ†ตํ•ด goroutine ๊ฐ„์˜ ํ†ต์‹ ์„ ์‰ฝ๊ฒŒ ํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•œ๋‹ค

ex)

package main
 
import (
    "fmt"
    "time"
)
 
func say(s string) {
    for i := 0; i < 10; i++ {
        fmt.Println(s, "---->", i)
    }
}
 
func main() {
    // 1. The Synchronous way
    say("Sync")
 
    // 2. Go routines
    go say("Async 1")
    go say("Async 2")
    go say("Async 3")
 
    // Sleep for 3 sec
    time.Sleep(time.Second * 3)
}

Last updated