go语言设计模式之Concurrency pipeline

Posted aguncn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
", res, test[1])
	}
}

  技术图片

以上是关于go语言设计模式之Concurrency pipeline的主要内容,如果未能解决你的问题,请参考以下文章

go语言设计模式之Concurrency pipeline

go语言设计模式之Concurrency workers pool

GO_11:GO语言基础之并发concurrency

GO语言基础之并发concurrency

GO语言的并发Concurrency:Goroutine与通信机制Channel

go14--并发concurrency,Goroutine ,channel