docs: channel

This commit is contained in:
Shikong 2021-11-09 00:59:23 +08:00
parent 6d9888b047
commit f4636be23b
2 changed files with 52 additions and 1 deletions

50
base/channel/main.go Normal file
View File

@ -0,0 +1,50 @@
package main
import (
"fmt"
"sync"
"time"
)
// 声明 通道中 元素类型
var b chan int
var wg = new(sync.WaitGroup)
func main() {
fmt.Println(b)
// 初始化 通道
// 通道需初始化后才能使用
// 一个没有缓冲区的通道
b = make(chan int)
fmt.Println(b)
// 带缓冲区的通道初始化
c := make(chan int, 16)
fmt.Println(c)
wg.Add(1)
// 由另一个 goroutine 负责接收
go func() {
fmt.Println("goroutine 接收: 等待接收 通道 b 中的值")
// 从通道 b 接收一个值
t := <-b
fmt.Println(t)
wg.Done()
}()
wg.Add(1)
go func() {
time.Sleep(500 * time.Millisecond)
fmt.Println("goroutine 发送: 将 10086 发送到 通道 b 中")
// 将 10086 发送至 通道 b 中
// 没人接收将会导致死锁
b <- 10086
wg.Done()
}()
wg.Wait()
}

View File

@ -32,7 +32,8 @@ func main() {
// goroutine 初始栈大小为2k
// 设置 最大 线程数
// 默认为 CPU 线程数
// 默认为 CPU 逻辑核心数
fmt.Printf("CPU 逻辑核心数: %d\n", runtime.NumCPU())
// 线程过多会增加 上下文切换负担
runtime.GOMAXPROCS(1)
wg.Add(2)