如何为GoLang的bufio.Writer设置写入截止时间?

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

How to set a write deadline for GoLang bufio.Writer?

问题

我正在使用Go语言中的bufio.Writer,代码如下所示。

conn, err := net.Dial("tcp", address) // address的格式为ip:port
w := bufio.NewWriter(conn)
w.WriteByte(code) // code是一个字节
w.Write(data) // data是一个字节缓冲区
w.Flush()

我正在尝试修改上述代码,使得write()事件具有截止时间:当截止时间到达时,无论成功与否,write()事件都将返回。

在Go语言中,如果直接使用conn(连接对象)进行写入,可以设置截止时间,例如conn.SetWriteDeadline(time.Now().Add(n * time.Second))。然而,当我使用bufio.Writer对象时,它实际上是对缓冲IO的conn进行封装,没有提供设置截止时间的API。

虽然可以使用conn.SetWriteDeadline(time.Now().Add(n * time.Second))并使用conn.Write(b),但这非常低效,因为它不会缓冲write事件(因此会有很多上下文切换)。

在Go语言中,是否有一种方法可以在使用缓冲IO时设置writeDeadline()

谢谢。

英文:

I am using buffio.Writer in GoLang as follows.

conn, err := net.Dial("tcp", address) // address is of form ip:port
w := bufio.NewWriter(conn)
w.WriteByte(code) // code is a byte
w.Write(data) // data is a byte buffer
w.Flush()

I am trying to modify the above code so that the write() events have a deadline: when the deadline is passed, the write() event will return irrespective of the fact that it was successful or not.

In GoLang its possible to have a deadline, if the conn (connection object) is directly used for writing using conn.SetWriteDeadline(time.Now().Add(n * time.Second)). However, when I use bufifo.writer object, which is essentially a wrapper around conn for buffered IO, there is no API to set a deadline.

While its possible to use conn.SetWriteDeadline(time.Now().Add(n * time.Second)) and use conn.Write(b), its very inefficient since it doesn't buffer the write events (thus a lot of context switches)

Is there a way in GoLang where I can use buffered IO with a writeDeadline()?

Thanks

答案1

得分: 1

这里有两种情况需要注意。

如果你想要每个write()操作都有截止时间,那么使用缓冲是不可能的。当你使用缓冲时,实际的write()操作会在缓冲区满时触发。所以从技术上讲,你无法知道你的write()操作何时完成。在这种情况下,你实际上是在使用conn.write(),你可以使用conn.SetWriteDeadline(time.Now().Add(n * time.Second))

在第二种情况下,正如@icza在评论中提到的,你可以在底层的conn对象中设置截止时间,而buffio.writer()包装器将遵循这个规则。虽然这在语义上是正确的,但它并没有提供你想要的网络抽象。

英文:

There are two cases to note here.

If you want to have per write() deadline, then its not possible to use buffering. When you use buffering, then the actual write() is triggered when the buffer is full. So technically its not possible to know when your write() is completed. In this case, you are essentially using conn.write() and you can use conn.SetWriteDeadline(time.Now().Add(n * time.Second)).

In the second case, as @icza has mentioned in the comment, you can set the deadline in the underlying conn object, and the buffio.writer() wrapper will adhere to this rule. While this is semantically correct, it doesn't provide the networking abstraction you want.

huangapple
  • 本文由 发表于 2022年3月22日 21:30:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/71572909.html
匿名

发表评论

匿名网友

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

确定