_CORE
AI & Agentic Systems Core Information Systems Cloud & Platform Engineering Data Platform & Integration Security & Compliance QA, Testing & Observability IoT, Automation & Robotics Mobile & Digital Banking & Finance Insurance Public Administration Defense & Security Healthcare Energy & Utilities Telco & Media Manufacturing Logistics & E-commerce Retail & Loyalty
References Technologies Blog Know-how Tools
About Collaboration Careers
CS EN
Let's talk

Go Concurrency — goroutines a channels

28. 10. 2024 1 min read intermediate

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

Key Takeaway

Goroutines pro lightweight concurrency, channels pro komunikaci, select pro multiplexing. Don’t communicate by sharing memory.

goconcurrencygoroutineschannels
Share:

CORE SYSTEMS tým

Stavíme core systémy a AI agenty, které drží provoz. 15 let zkušeností s enterprise IT.