Goroutine là lightweight thread do Go runtime quản lý.
- Khác OS thread: goroutine stack default ~8KB, tự grow/shrink; Go scheduler multiplex goroutines lên OS threads (M:N scheduling).
- Có thể chạy hàng triệu goroutines cùng lúc.
go
func fetchData(url string) {
resp, err := http.Get(url)
if err != nil {
log.Println(err)
return
}
defer resp.Body.Close()
// xử lý response...
}
func main() {
urls := []string{"https://a.com", "https://b.com", "https://c.com"}
for _, url := range urls {
go fetchData(url) // mỗi request chạy goroutine riêng
}
time.Sleep(2 * time.Second) // đợi goroutines (dùng WaitGroup tốt hơn)
}A goroutine is a lightweight thread managed by the Go runtime.
- It starts with ~8KB stack that grows/shrinks dynamically (OS threads have fixed 1-8MB).
- The Go scheduler multiplexes goroutines onto OS threads (M:N scheduling).
- You can run millions concurrently.
go
func fetchData(url string) {
resp, err := http.Get(url)
if err != nil {
log.Println(err)
return
}
defer resp.Body.Close()
// process response...
}
func main() {
urls := []string{"https://a.com", "https://b.com", "https://c.com"}
for _, url := range urls {
go fetchData(url) // each request runs in its own goroutine
}
time.Sleep(2 * time.Second) // wait (use WaitGroup in practice)
}