How to wait until buffered channel (semaphore) is empty?

前端 未结 4 1890
遥遥无期
遥遥无期 2020-12-19 02:36

I have a slice of integers, which are manipulated concurrently:

ints := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

I\'m using a buffered channel

4条回答
  •  生来不讨喜
    2020-12-19 03:18

    Use "worker pool" to process you data. It is cheeper than run goroutine for each int, allocate memory for variables inside it and so on...

    ints := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    
    ch := make(chan int)
    
    var wg sync.WaitGroup
    
    // run worker pool
    for i := 2; i > 0; i-- {
        wg.Add(1)
    
        go func() {
            defer wg.Done()
    
            for id := range ch {
                // do something
                fmt.Println(id)
            }
        }()
    }
    
    // send ints to workers
    for _, i := range ints {
        ch <- i
    }
    
    close(ch)
    
    wg.Wait()
    

提交回复
热议问题