在Go中释放通道

huangapple go评论71阅读模式
英文:

Releasing channel in Go

问题

我有一个TCP套接字和2个goroutine在读写流。我正在编写一个goroutine,从一个通道中读取数据。如果TCP连接断开,那么来自goroutine的读取将检测到错误并停止。但是,我如何释放一个有goroutine写入的通道?是否有像chan.release()这样的方法,或者我应该发送一个特殊的数据包来告诉goroutine结束?

英文:

I have a TCP socket and 2 goroutines reading and writing to streams.
I am writing a goroutine that reads data from a channel.
If the TCP connection is dropped then the read from the go routine will detect an error and stop.

But how do I release a channel that has a goroutine writing to?

Is there method like chan.release() or should I post a special packet that will tell the goroutine to end?

答案1

得分: 5

close(ch)将关闭通道。

如果您正在遍历通道,则当通道关闭时,for循环将退出。
val, ok := <-ch允许您检查关闭的通道。如果ch关闭,则ok将是一个布尔值,如果ch打开,则为true。

英文:

close(ch) will close the channel.

If you are ranging over the channel then the for loop will exit when the channel is closed.
val, ok := &lt;-ch allow you to check for closed channels. ok will be a boolean value with false if the ch is closed true if the ch is open.

huangapple
  • 本文由 发表于 2013年2月13日 01:11:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/14837970.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定