github.com/songzhibin97/gkit@v1.2.13/concurrent/fan_out.go (about)

     1  package concurrent
     2  
     3  import "sync"
     4  
     5  // FanOut 扇出模式
     6  func FanOut(in <-chan interface{}, out []chan interface{}, async bool) {
     7  	wg := sync.WaitGroup{}
     8  	go func() {
     9  		defer func() {
    10  			wg.Wait()
    11  			for i := 0; i < len(out); i++ {
    12  				close(out[i])
    13  			}
    14  		}()
    15  		for v := range in {
    16  			for i := 0; i < len(out); i++ {
    17  				if async {
    18  					// 异步
    19  					wg.Add(1)
    20  					go func(ch chan interface{}, v interface{}) {
    21  						defer wg.Done()
    22  						ch <- v
    23  					}(out[i], v)
    24  				} else {
    25  					// 同步
    26  					out[i] <- v
    27  				}
    28  			}
    29  		}
    30  	}()
    31  }