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