Go併發模式之將channel一分爲二(tee channel)

想把一個channel 一變二;以便 將它們發送到 代碼的兩個不同獨立區域中。
func main() {
	tee := func(done <-chan interface{}, in <- chan interface{})( <-chan interface{}, <-chan interface {}) {
		out1 := make(chan interface{})
		out2 := make(chan interface{})

		go func() {
			defer close(out1)
			defer close(out2)
			for val := range orDone(done, in){
				//使用out1, out2的本地化版本
				var out1, out2 = out1, out2
				for i := 0; i < 2; i++{
					select {
					case <- done :
					case out1<- val:
						out1 = nil
					case out2<- val:
						out2 = nil
					}
				}
			}

		}()
		return out1, out2
	}

	done :=make(chan interface{})
	defer close(done)
	out1, out2 := tee(done, take(done, repeat(done,1,2), 4))

	for val1 := range out1{
		//fmt.Printf("out1:%v, out2:%v\n", val1, <-out2)
		fmt.Printf("out1:%v", val1)
	}
	//time.Sleep(5*time.Second)
	for val2 := range out2{
		fmt.Printf("out1:%v", val2)
	}

}

/**
缺點 必須
同時 從 out1  和 out2 中讀取數據, 只讀一個 會造成死鎖!!!
 */

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章