Sirui Zhuang
Sirui Zhuang

Reputation: 885

Golang 1.5 io.Copy blocked with two TCPConn

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?

Upvotes: 2

Views: 2204

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109336

Previously, you were getting lucky when the timing of the syscalls would cause a write error in your second io.Copy [line 41]. (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()
}()

Upvotes: 4

Related Questions