// relay copies between left and right bidirectionally. Returns number of
// bytes copied from right to left, from left to right, and any error occurred.
func relay(left, right net.Conn) (int64, int64, error) {
type res struct {
N int64
Err error
}
ch := make(chan res)
go func() {
n, err := io.Copy(right, left)
right.SetDeadline(time.Now()) // wake up the other goroutine blocking on right
left.SetDeadline(time.Now()) // wake up the other goroutine blocking on left
ch <- res{n, err}
}()
n, err := io.Copy(left, right)
right.SetDeadline(time.Now()) // wake up the other goroutine blocking on right
left.SetDeadline(time.Now()) // wake up the other goroutine blocking on left
rs := <-ch
if err == nil {
err = rs.Err
}
return n, rs.N, err
}这是来自go-shadowsocks2项目,但是,我不能理解left.SetDeadline(time.Now())部分,注释(唤醒左边的另一个goroutine阻塞)是什么意思?
带有time.Now()参数的SetDeadline看起来很不寻常,有谁能帮我理解一下吗?
发布于 2020-08-20 22:51:01
这可能会有所帮助,请参阅net.Conn文档:
截止日期是I/O操作失败而不是阻塞的绝对时间。截止日期适用于所有将来和挂起的I/O,而不仅仅是紧随其后的读或写调用。超过截止日期后,可以通过在将来设置截止日期来刷新连接。
看起来好像有两个goroutine将数据从一个连接复制到另一个连接。当其中任何一个操作的源连接关闭时,该复制操作将终止,但另一个复制操作将被阻止。根据net.Conn文档,通过设置超时将导致阻塞的复制操作失败,从而解除阻塞的gouroutine例程。
https://stackoverflow.com/questions/63507517
复制相似问题