码迷,mamicode.com
首页 > 编程语言 > 详细

go语言设计模式之Concurrency pipeline

时间:2019-11-24 11:47:51      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:pack   Go语言   bool   cti   second   line   sum   tin   turn   

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

标签:pack   Go语言   bool   cti   second   line   sum   tin   turn   

原文地址:https://www.cnblogs.com/aguncn/p/11921552.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!