初始化Go学习项目
This commit is contained in:
28
go-channel-practice/directional.go
Normal file
28
go-channel-practice/directional.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
// 只负责发送数据
|
||||
func producer(out chan<- int) {
|
||||
for i := 1; i <= 5; i++ {
|
||||
fmt.Println("[Producer] 发送:", i)
|
||||
out <- i
|
||||
}
|
||||
fmt.Println("[Producer] 关闭 channel")
|
||||
close(out) // 只有发送方才能关闭
|
||||
}
|
||||
|
||||
// 只负责接收数据
|
||||
func consumer(in <-chan int) {
|
||||
for v := range in { // 直到 channel 被关闭
|
||||
fmt.Println("[Consumer] 接收:", v)
|
||||
}
|
||||
fmt.Println("[Consumer] channel 已关闭,接收结束")
|
||||
}
|
||||
|
||||
func main() {
|
||||
ch := make(chan int)
|
||||
|
||||
go producer(ch) // ch 在这里被当作 只发送 channel 使用
|
||||
consumer(ch) // ch 在这里被当作 只接收 channel 使用
|
||||
}
|
||||
Reference in New Issue
Block a user