Golang 1.5 io.Copy在两个TCPConn上被阻塞。

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

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

. (Ignoring errors tends to hide bugs)

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()
}()

huangapple
  • 本文由 发表于 2015年9月8日 22:38:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/32460618.html
匿名

发表评论

匿名网友

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

确定