Sobes.tech
Junior — Middle

Beshta ishga tushirilgan beshta goroutine natijalarini qanday yig'ish va qayta ishlash mumkin?

sobes.tech AI

AIdan javob

Go'da bir necha goroutine'i aynı anda başlatıp sonuçlarını toplamak için kanalları (channels) kullanabilirsiniz. Her goroutine sonucu kanala gönderir ve ana fonksiyon kanaldan gerekli sayıda okuma yapar.

Örnek:

package main

import (
    "fmt"
    "sync"
)

func worker(id int, ch chan<- int, wg *sync.WaitGroup) {
    defer wg.Done()
    // bazı işler
    result := id * 2
    ch <- result
}

func main() {
    ch := make(chan int, 5) // tamponlu kanal
    var wg sync.WaitGroup

    for i := 1; i <= 5; i++ {
        wg.Add(1)
        go worker(i, ch, &wg)
    }

    wg.Wait()
    close(ch)

    for res := range ch {
        fmt.Println("Sonuç:", res)
    }
}

Burada, worker sonucu hesaplayan ve kanala gönderen bir goroutinedir. Ana fonksiyon, WaitGroup ile tüm goroutinelerin tamamlanmasını bekler, sonra kanalı kapatır ve tüm sonuçları okur.