Go concurrency model je elegantní — goroutines jsou lehké ‘thready’, channels jsou komunikační kanály mezi nimi.
Goroutines¶
func fetchURL(url string, ch chan<- string) { resp, err := http.Get(url) if err != nil { ch <- fmt.Sprintf(“Error: %s”, err) return } ch <- fmt.Sprintf(“%s: %d”, url, resp.StatusCode) } func main() { urls := []string{“https://google.com”, “https://github.com”} ch := make(chan string, len(urls)) for _, url := range urls { go fetchURL(url, ch) } for range urls { fmt.Println(<-ch) } }
Select¶
select { case msg := <-ch1: fmt.Println(“ch1:”, msg) case msg := <-ch2: fmt.Println(“ch2:”, msg) case <-time.After(5 * time.Second): fmt.Println(“timeout”) }
sync.WaitGroup¶
var wg sync.WaitGroup for _, url := range urls { wg.Add(1) go func(u string) { defer wg.Done() fetch(u) }(url) } wg.Wait()
Klíčový takeaway¶
Goroutines pro lightweight concurrency, channels pro komunikaci, select pro multiplexing. Don’t communicate by sharing memory.