Goroutine
Goroutine
A lightweight thread in the Go language. Thousands can run concurrently using less memory than OS threads. Created with the go keyword.
Goroutine
A lightweight thread in the Go language. Thousands can run concurrently using less memory than OS threads. Created with the go keyword.
A goroutine is a lightweight thread provided by the Go language and a core element of concurrent programming. While an OS thread typically uses a stack of 1MB or more, a goroutine starts with a stack of about 2KB and grows dynamically as needed.
A goroutine is created by writing a function call with the go keyword. The Go runtime's scheduler performs M:N scheduling (mapping M goroutines onto N OS threads), efficiently managing thousands to millions of goroutines.
Communication between goroutines takes place through channels. Following Go's philosophy, "Do not communicate by sharing memory; instead, share memory by communicating," using channels makes it possible to write safe concurrent code even without locks.
Because goroutines are very cheap to create, it is common to create a new goroutine for each request on a server. However, you need to watch out for goroutine leaks (leaky goroutines), and it is important to terminate them properly using context.
package main
import (
"fmt"
"sync"
"time"
)
// 기본 고루틴 생성
func sayHello(name string) {
fmt.Printf("Hello, %s!\n", name)
}
func main() {
// go 키워드로 고루틴 생성
go sayHello("World")
// 채널을 통한 고루틴 간 통신
ch := make(chan int, 3)
// 생산자 고루틴
go func() {
for i := 1; i <= 3; i++ {
ch <- i
fmt.Printf("Sent: %d\n", i)
}
close(ch)
}()
// 소비자 (메인 고루틴)
for num := range ch {
fmt.Printf("Received: %d\n", num)
}
// WaitGroup으로 여러 고루틴 동기화
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
time.Sleep(100 * time.Millisecond)
fmt.Printf("Worker %d done\n", id)
}(i)
}
wg.Wait() // 모든 고루틴 완료 대기
fmt.Println("All workers completed")
}
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free