go语言:带缓冲和不带缓冲通道的区别

不带缓冲的通道

这种类型的通道要求发送 goroutine 和接收 goroutine 同时准备好,才能完成发送和接收操作。

package main

import (
	"fmt"
	"time"
)

func main()  {

	c := make(chan int, 0)

	go func() {
		defer func() {
			fmt.Println("recycle")
		}()
		a := <- c
		fmt.Println("read",a)
	}()

	c <- 11
	fmt.Println("write")

	time.Sleep(time.Second*5)
}

输出:

read 11
recycle
write

可以看出发送端会一直阻塞到这个goroutine完全退出。

带缓冲的通道

上面代码第10行,改成缓冲为1个的通道

c := make(chan int, 1)

输出:

write
read 11
recycle

就变成了:我先走了,你们慢慢退出。

发布了19 篇原创文章 · 获赞 2 · 访问量 680

猜你喜欢

转载自blog.csdn.net/weixin_43465618/article/details/104589869