关闭chan的时候需要注意哪些问题?

假设A、B两个routine利用一个chan收发数据,A收,B发,那么应该由谁来关闭chan?如果两个都不应该做关闭chan这个事情,应该怎么处理?

共 4 个回复


stevewang

B关闭channel,A收到关闭消息后结束当前任务。

# 0

xinyu391

当然是最后接触chan的 负责关闭了啊

# 1

nzai

B负责关闭chan,关闭后A依然可以从chan中读出剩余未读数据,并且A可以判读chan是否关闭了

i, ok := <- ch 
if ok { 
    println(i) 
} else { 
    println("channel closed") 
}
# 2

JY115

Go内置函数close()官方文档介绍

// The close built-in function closes a channel, which must be either
// bidirectional or send-only. It should be executed only by the sender,
// never the receiver, and has the effect of shutting down the channel after
// the last sent value is received. After the last value has been received
// from a closed channel c, any receive from c will succeed without
// blocking, returning the zero value for the channel element. The form
//    x, ok := <-c
// will also set ok to false for a closed channel.
func close(c chan<- Type)
# 3