question about net Buffers.WriteTo method

95 views
Skip to first unread message

Jamil Djadala

unread,
Jan 15, 2025, 7:07:21 AM1/15/25
to golang-nuts

Hi,
As i understand, WriteTo is used to optimize write of multiple buffers
to socket, using writev. But writev also ensure that these multiple
buffers are written atomically, in case of concurrent writes, bytes
from concurrent write are not inserted between buffers of writev.

https://cs.opensource.google/go/go/+/refs/tags/go1.23.4:src/net/net.go;l=841

As can i see, in general case (when io.Writer does not implement
buffersWriter), buffers are written by ranging over them and using
Write, which does not ensure atomic write of all buffers.
I think proper implementation should consolidate all buffers in 1
buffer (yes, allocate memory), and write this one with Write.

Does i miss something ?
Is current implementation are correct ?

--
Jamil Djadala

Ian Lance Taylor

unread,
Jan 15, 2025, 8:29:27 PM1/15/25
to Jamil Djadala, golang-nuts
The net.WriteBuffers type exists to permit code to easily take
advantage of the writev system call when it is available. However, the
Go methods Write and WriteTo, as defined by the io.Writer and
io.WriterTo interfaces, make no promises as to how many times they
will call the write or writev system calls. That is in some ways a
level confusion. A program can perfectly reasonably use net.Buffers
with an io.Writer that is not any sort of system description, for
which writev doesn't make any sense anyhow.

So, yes, the current implementation is OK. Programs that must
guarantee atomic calls to write or writev must use the
golang.org/x/sys/unix package, not the net package. The Go standard
library doesn't provide guarantees at that level.

Ian
Reply all
Reply to author
Forward
0 new messages