15

golang的chan特性

 3 years ago
source link: https://studygolang.com/articles/31838
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

go routine之间可以通过channel来通信。

1、单向channel&双向channel

<-chan只能用来发送的单向channel;chan<-只能用来接收的单向channel;chan双向channel 向<-chan发送数据 或者 接收chan<-的数据;编译失败

var cc = make(<-chan int)
	close(cc)
	cc <- 23
# command-line-arguments
.\main.go:48:7: invalid operation: close(cc) (cannot close receive-only channel)
.\main.go:49:5: invalid operation: cc <- 23 (send to receive-only type <-chan int)
var cc = make(chan<- int)
	v:= <-cc
# command-line-arguments
.\main.go:49:6: invalid operation: <-cc (receive from send-only type chan<- int)

单向channel的应用场景是什么呢,回头研究一下。

2、channel的声明声明一个传输整形的buffer chan,容量为6:

var cc = make(chan int, 6)

读缓存中为空的channel和写入缓存已满的channel都是阻塞的

因此,声明channel必须指定容量,channel才"可用",否则channel的读写是阻塞的

3、channel使用完毕,使用close(c chan<- Type)关闭channel

向关闭的channel发送数据,会导致panic

***
	var cc = make(chan int,1)
	close(cc)
	cc <- 23
	***

panic: send on closed channel

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK