Go 并发编程深入解析
1. nil 通道
在 Go 语言中,nil 通道总是会阻塞。当你有意想要这种阻塞行为时,就可以使用 nil 通道。以下是一个示例代码:
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
var wg sync.WaitGroup
func add(c chan int) {
sum := 0
t := time.NewTimer(time.Second)
for {
select {
case input := <-c:
sum = sum + input
case <-t.C:
c = nil
fmt.Println(sum)
wg.Done()
}
}
}
func send(c chan int) {
for {
c <- rand.Intn(10)
}
}
func main() {
c := make(chan int)
rand.Seed(time.Now().Unix())
wg.Add(1)
go add(c)
go send(c)
wg.Wait()
}
这个程序的执行流程如下:
1. main 函数创建一个整数通道 c
超级会员免费看
订阅专栏 解锁全文
1319

被折叠的 条评论
为什么被折叠?



