代码之家  ›  专栏  ›  技术社区  ›  overexchange

如何等待go例程完成?

  •  0
  • overexchange  · 技术社区  · 4 年前

    以下是场景:

    inputCh := g(abc) // return <- chan []string
    
    
    slice := make([]map[string][]string, 0)
    m := sync.Mutex{}
    for whatever := range inputCh {
        go func(whatever []string) {
            matches := f(xyz, whatever) // returns map[string][]string
            m.Lock()
            slice = append(slice, matches)
            m.Unlock()
        }(whatever)
    }
    
    z := merge(slice...)
    

    inputCh close(inputCh) )

    merge(slice...) 只有在所有的围棋程序完成并更新之后 slice


    不确定,如果 sync.WaitGroup 可以使用。

    如何保证 合并(切片…) 仅在 被所有围棋程序更新?

    0 回复  |  直到 4 年前
        1
  •  1
  •   kozmo    4 年前

    使用 sync.WaitGroup 检查通道何时关闭

    var wg sync.WaitGroup
    
    for {
        whatever, ok := <-inputCh
        if !ok { // check inputCh is close
            break
        }
        // add delta
        wg.Add(1)
        go func(whatever []string) {
            matches := f(xyz, whatever)
            m.Lock()
            slice = append(slice, matches)
            m.Unlock()
            // goroutine is done
            wg.Done()
        }(whatever)
    }
    
    // waits until all the goroutines call "wg.Done()"
    wg.Wait()
    
        2
  •  -3
  •   M. Ekin Uygur    4 年前

    你可以用 sync.WaitGroup

    // create a work group
    var wg sync.WaitGroup
    // add delta
    wg.Add(len(inputCh))
    
    slice := make([]map[string][]string, 0)
    m := sync.Mutex{}
    for whatever := range inputCh {
        go func(whatever []string) {
            matches := f(xyz, whatever) // returns map[string][]string
            m.Lock()
            slice = append(slice, matches)
            m.Unlock()
            // signal work group that the routine is done
            wg.Done()
        }(whatever)
    }
    // waits until all the go routines call wg.Done()
    wg.Wait()