英文:
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 := <-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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论