Nâng CaoGolang iconGolang

Worker pool pattern trong Go?

Tạo fixed number goroutines (workers) đọc jobs từ channel, giới hạn concurrency và tránh tạo quá nhiều goroutines.

go
func worker(id int, jobs <-chan Job, results chan<- Result, wg *sync.WaitGroup) {
    defer wg.Done()
    for j := range jobs {
        results <- process(j)
    }
}

func main() {
    jobs := make(chan Job, 100)
    results := make(chan Result, 100)
    var wg sync.WaitGroup
    for i := 0; i < 5; i++ { // 5 workers
        wg.Add(1)
        go worker(i, jobs, results, &wg)
    }
    for _, j := range allJobs { jobs <- j }
    close(jobs)
    wg.Wait()
    close(results)
}

Xem toàn bộ Golang cùng filter theo level & chủ đề con.

Mở danh sách Golang