mirror of
https://gitee.com/shikong-sk/golang-study
synced 2025-02-23 15:32:15 +08:00
docs: channel
This commit is contained in:
parent
016c89dfd2
commit
9e6e47b4c9
@ -6,12 +6,11 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// 声明 通道中 元素类型
|
|
||||||
var b chan int
|
|
||||||
|
|
||||||
var wg = new(sync.WaitGroup)
|
var wg = new(sync.WaitGroup)
|
||||||
|
|
||||||
func main() {
|
func noBuffChannel() {
|
||||||
|
// 声明 通道中 元素类型
|
||||||
|
var b chan int
|
||||||
fmt.Println(b)
|
fmt.Println(b)
|
||||||
|
|
||||||
// 初始化 通道
|
// 初始化 通道
|
||||||
@ -20,10 +19,6 @@ func main() {
|
|||||||
b = make(chan int)
|
b = make(chan int)
|
||||||
fmt.Println(b)
|
fmt.Println(b)
|
||||||
|
|
||||||
// 带缓冲区的通道初始化
|
|
||||||
c := make(chan int, 16)
|
|
||||||
fmt.Println(c)
|
|
||||||
|
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
// 由另一个 goroutine 负责接收
|
// 由另一个 goroutine 负责接收
|
||||||
go func() {
|
go func() {
|
||||||
@ -32,6 +27,9 @@ func main() {
|
|||||||
t := <-b
|
t := <-b
|
||||||
fmt.Printf("goroutine 接收: %d\n", t)
|
fmt.Printf("goroutine 接收: %d\n", t)
|
||||||
|
|
||||||
|
// 关闭通道
|
||||||
|
close(b)
|
||||||
|
|
||||||
wg.Done()
|
wg.Done()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
@ -45,6 +43,36 @@ func main() {
|
|||||||
|
|
||||||
wg.Done()
|
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()
|
wg.Wait()
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user