英文:
Golang 1.5 io.Copy blocked with two TCPConn
问题
io.Copy
方法在Go 1.5中返回的时间是什么时候?
英文:
http://play.golang.org/p/gZo5RqgY4F
I have a question with io.Copy
method. The link above will block in line 44 under Go 1.5. But will pass in 1.4.2. I have no idea with this issue.
Here is my go version: go version go 1.5 darwin/amd64
.
When did the io.Copy
return in go 1.5?
答案1
得分: 4
之前,在第41行的第二个io.Copy
中,当系统调用的时间导致写入错误时,你运气好。 (忽略错误往往会隐藏错误)
这纯粹是偶然发生的(甚至可能是错误的)。由于该复制的源连接(conn2
)从未关闭,io.Copy
从未收到io.EOF
并且不返回。您需要在每个复制的goroutine中关闭对立连接,以解除对io.Copy
的另一个调用的阻塞。
wg.Add(1)
go func() {
io.Copy(conn1, conn2)
// conn2已返回EOF或错误,因此我们需要关闭双工复制的另一半。
conn1.Close()
wg.Done()
}()
wg.Add(1)
go func() {
io.Copy(conn2, conn1)
conn2.Close()
wg.Done()
}()
英文:
Previously, you were getting lucky when the timing of the syscalls would cause a write error in your second io.Copy
This was purely by accident (and may even be incorrect). Since the source connection of that copy (conn2
) is never closed, the io.Copy
never receives an io.EOF
and doesn't return. You need to close the opposing connection in each of the copy goroutines to unblock the other's call to io.Copy
.
wg.Add(1)
go func() {
io.Copy(conn1, conn2)
// conn2 has returned EOF or an error, so we need to shut down the
// other half of the duplex copy.
conn1.Close()
wg.Done()
}()
wg.Add(1)
go func() {
io.Copy(conn2, conn1)
conn2.Close()
wg.Done()
}()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论