diff --git a/base/channel/main.go b/base/channel/main.go index 8b34141..3daa8ff 100644 --- a/base/channel/main.go +++ b/base/channel/main.go @@ -6,12 +6,11 @@ import ( "time" ) -// 声明 通道中 元素类型 -var b chan int - var wg = new(sync.WaitGroup) -func main() { +func noBuffChannel() { + // 声明 通道中 元素类型 + var b chan int fmt.Println(b) // 初始化 通道 @@ -20,10 +19,6 @@ func main() { b = make(chan int) fmt.Println(b) - // 带缓冲区的通道初始化 - c := make(chan int, 16) - fmt.Println(c) - wg.Add(1) // 由另一个 goroutine 负责接收 go func() { @@ -32,6 +27,9 @@ func main() { t := <-b fmt.Printf("goroutine 接收: %d\n", t) + // 关闭通道 + close(b) + wg.Done() }() @@ -45,6 +43,36 @@ func main() { wg.Done() }() +} +func buffChannel() { + // 带缓冲区的通道初始化 + b := make(chan int, 1) + + go func() { + // 使用 for...range 从通道读取值 + for t := range b { + fmt.Printf("goroutine 接收: %d\n", t) + } + }() + + fmt.Println("goroutine 发送: 将 10086 发送到 通道 b 中") + b <- 10086 + + // 当缓冲区满了 没人接收也会导致死锁 + fmt.Println("goroutine 发送: 将 1008611 发送到 通道 b 中") + b <- 1008611 + + // 关闭通道 + close(b) +} + +func main() { + noBuffChannel() + wg.Wait() + + fmt.Println("=========================================================") + + buffChannel() wg.Wait() }