初始化Go学习项目
This commit is contained in:
37
go-channel-practice/pipeline.go
Normal file
37
go-channel-practice/pipeline.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
// 生产者:产生 1~5
|
||||
func producer1(out chan<- int) {
|
||||
for i := 1; i <= 5; i++ {
|
||||
fmt.Println("[Producer] 发送:", i)
|
||||
out <- i
|
||||
}
|
||||
close(out)
|
||||
}
|
||||
|
||||
// 处理者:把数字放大 10 倍
|
||||
func multiplier(in <-chan int, out chan<- int) {
|
||||
for v := range in {
|
||||
fmt.Println("[Multiplier] 接收:", v)
|
||||
out <- v * 10
|
||||
}
|
||||
close(out)
|
||||
}
|
||||
|
||||
// 消费者:打印结果
|
||||
func consumer1(in <-chan int) {
|
||||
for v := range in {
|
||||
fmt.Println("[Consumer] 最终结果:", v)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
ch1 := make(chan int, 2) // 有缓冲,减轻 producer 阻塞
|
||||
ch2 := make(chan int, 2)
|
||||
|
||||
go producer1(ch1)
|
||||
go multiplier(ch1, ch2)
|
||||
consumer1(ch2)
|
||||
}
|
||||
Reference in New Issue
Block a user