[Go] goroutine Basic

bltn·2021년 12월 29일
0

golang

목록 보기
1/3
post-thumbnail

A goroutine is a lightweight thread of execution.

package main

import (
    "fmt"
    "time"
)

func f(from string) {
    for i := 0; i < 3; i++ {
        fmt.Println(from, ":", i)
    }
}

func main() {

    f("direct") // 절차적으로 실행

    go f("goroutine") // goroutine 으로 실행

    go func(msg string) {
        fmt.Println(msg)
    }("going") // goroutine 으로 실행

    time.Sleep(time.Second) // 1초 Sleep, main 함수가 끝나면 goroutine 은 작동하지 않기에
    fmt.Println("done")
}
$ go run goroutines.go
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
done

Reference

Go by Example: Goroutines

0개의 댓글