Přeskočit na obsah
_CORE
AI & Agentic Systems Core Informační Systémy Cloud & Platform Engineering Data Platforma & Integrace Security & Compliance QA, Testing & Observability IoT, Automatizace & Robotika Mobile & Digital Banky & Finance Pojišťovnictví Veřejná správa Obrana & Bezpečnost Zdravotnictví Energetika & Utility Telco & Média Průmysl & Výroba Logistika & E-commerce Retail & Loyalty
Reference Technologie Blog Know-how
Nástroje O nás Spolupráce Kariéra
Pojďme to probrat

Go Concurrency — goroutines a channels

28. 10. 2024 1 min čtení 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()

Klíčový takeaway

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

goconcurrencygoroutineschannels
Sdílet:

CORE SYSTEMS tým

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