💻 Programming

Goroutine

Goroutine

A lightweight thread in the Go language. Thousands can run concurrently using less memory than OS threads. Created with the go keyword.

📖 Detailed Explanation

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.

💻 Code Example

Go
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")
}

🗣️ Examples of Practical Conversations

Backend developer
"Our API server calls 3 external services, and doing it sequentially makes responses slow. What if we process them in parallel with goroutines?"
Senior developer
"Good idea. If you use the errgroup package, you can make the calls in parallel and handle errors cleanly as well."
Backend developer
"If we also set a timeout with context, the whole request won't block even if one of them is slow."
Interviewer
"Please explain the difference between goroutines and OS threads."
Candidate
"A goroutine is a lightweight thread managed by the Go runtime. Its stack is small and grows dynamically, and its context-switching cost is much lower than that of OS threads. With M:N scheduling, it maps many goroutines onto a small number of OS threads."
Interviewer
"What is a goroutine leak, and how do you prevent it?"
Candidate
"A leak occurs when a goroutine waiting on a channel never wakes up. You need to propagate a cancellation signal with context.WithCancel or context.WithTimeout, and handle ctx.Done() in the select statement."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Reviewer
"This goroutine is capturing the loop variable directly. Before Go 1.22, a closure bug can occur."
Author
"Ah, right. I'll fix it to pass it as a parameter or assign it to a new variable inside the loop."
Reviewer
"Also, if you don't close the channel, the side reading with range will block forever. Please add a close call after sending is done."

⚠️ Cautions

🔗 Related Terms

📚 Learn More