github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/app/bconcurrent/fan_out.go (about)

     1  package bconcurrent
     2  
     3  import "sync"
     4  
     5  // FanOut 扇出模式
     6  func FanOut[T any](in <-chan T, out []chan T, 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 T, v T) {
    21  						defer wg.Done()
    22  						ch <- v
    23  					}(out[i], v)
    24  				} else {
    25  					// 同步
    26  					out[i] <- v
    27  				}
    28  			}
    29  		}
    30  	}()
    31  }