go语言设计模式之Concurrency pipeline

pipeline.go

package pipeline

func LaunchPipeline(amount int) int {
	firstCh := generator(amount)
	secondCh := power(firstCh)
	thirdCh := sum(secondCh)

	result := <-thirdCh
	return result
}

/*
func functionName(in <-chan int) <-chan int {
	out := make(chan bool, 100)

	go func() {
		for v := range in {
			//nothing
		}
		close(out)
	}()
	return out
}
*/
func generator(max int) <-chan int {
	outChInt := make(chan int, 100)

	go func() {
		for i := 1; i <= max; i++ {
			outChInt <- i
		}
		close(outChInt)
	}()
	return outChInt
}

func power(in <-chan int) <-chan int {
	out := make(chan int, 100)

	go func() {
		for v := range in {
			out <- v * v
		}
		close(out)
	}()
	return out
}

func sum(in <-chan int) <-chan int {
	out := make(chan int, 100)
	go func() {
		var sum int
		for v := range in {
			sum += v
		}
		out <- sum
		close(out)
	}()
	return out
}

  

pipeline_test.go

package pipeline

import "testing"

func TestLaunchPipeline(t *testing.T) {
	tableTest := [][]int{
		{3, 14},
		{5, 55},
	}
	var res int
	for _, test := range tableTest {
		res = LaunchPipeline(test[0])
		if res != test[1] {
			t.Fatal()
		}
		t.Logf("%d == %d\n", res, test[1])
	}
}

  go语言设计模式之Concurrency pipeline

上一篇:java-在测试中:参数[RedirectAttributes]的类型为Model或Map,但不能从实际模型中分配.您可能需要


下一篇:【原创】大叔经验分享(29)cdh5使用已存在的metastore数据库部署hive