Go bytes.Buffer是线程安全的吗?

时间:2013-10-28 23:07:06

标签: go

在Go编程语言中,bytes.Buffer是否是线程安全的? AFAIK,its documentation没有提到线程安全。

3 个答案:

答案 0 :(得分:20)

没有

Go文档遵循一条简单的规则:如果未明确声明对某些内容的并发访问是安全的,则不是。

答案 1 :(得分:11)

否 - 但您可以轻松地将其包装在线程安全的结构中!

对于简单的事情:

type Buffer struct {
    b bytes.Buffer
    m sync.Mutex
}
func (b *Buffer) Read(p []byte) (n int, err error) {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.Read(p)
}
func (b *Buffer) Write(p []byte) (n int, err error) {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.Write(p)
}
func (b *Buffer) String() string {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.String()
}

..并照常使用var buf Buffer等等。

想要更多的bytes.Buffer?随意挑选樱桃:

func (b *Buffer) Bytes() []byte {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.Bytes()
}
func (b *Buffer) Cap() int {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.Cap()
}
func (b *Buffer) Grow(n int) {
    b.m.Lock()
    defer b.m.Unlock()
    b.b.Grow(n)
}
func (b *Buffer) Len() int {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.Len()
}
func (b *Buffer) Next(n int) []byte {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.Next(n)
}
func (b *Buffer) ReadByte() (c byte, err error) {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.ReadByte()
}
func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.ReadBytes(delim)
}
func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.ReadFrom(r)
}
func (b *Buffer) ReadRune() (r rune, size int, err error) {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.ReadRune()
}
func (b *Buffer) ReadString(delim byte) (line string, err error) {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.ReadString(delim)
}
func (b *Buffer) Reset() {
    b.m.Lock()
    defer b.m.Unlock()
    b.b.Reset()
}
func (b *Buffer) Truncate(n int) {
    b.m.Lock()
    defer b.m.Unlock()
    b.b.Truncate(n)
}
func (b *Buffer) UnreadByte() error {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.UnreadByte()
}
func (b *Buffer) UnreadRune() error {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.UnreadRune()
}
func (b *Buffer) WriteByte(c byte) error {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.WriteByte(c)
}
func (b *Buffer) WriteRune(r rune) (n int, err error) {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.WriteRune(r)
}
func (b *Buffer) WriteString(s string) (n int, err error) {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.WriteString(s)
}
func (b *Buffer) WriteTo(w io.Writer) (n int64, err error) {
    b.m.Lock()
    defer b.m.Unlock()
    return b.b.WriteTo(w)
}

答案 2 :(得分:4)

使用io.Pipe()函数调用,它提供一对连接对象(*PipeReader*PipeWriter)用于同步读/写。这可以并行完成,它是一个线程安全的。