Go中可以使用“+”合并字符串,但是這種合并方式效率非常低店溢,每合并一次瘫筐,都是創(chuàng)建一個新的字符串,就必須遍歷復制一次字符串。Java中提供StringBuilder類(最高效,線程不安全)來解決這個問題晨川。Go中也有類似的機制,那就是Buffer(線程不安全)删豺。
以下是示例代碼:
package main
import (
"bytes"
"fmt"
)
func main() {
var buffer bytes.Buffer
for i := 0; i < 1000; i++ {
buffer.WriteString("a")
}
fmt.Println(buffer.String())
}
使用bytes.Buffer來組裝字符串共虑,不需要復制,只需要將添加的字符串放在緩存末尾即可吼鳞。
Buffer為什么線程不安全?
The Go documentation follows a simple rule: If it is not explicitly stated that concurrent access to something is safe, it is not.
Go文檔遵循一個簡單的規(guī)則:如果沒有明確聲明并發(fā)訪問某事物是安全的看蚜,則不是。
以下是Golang中bytes.Buffer部分源碼
// A Buffer is a variable-sized buffer of bytes with Read and Write methods.
// The zero value for Buffer is an empty buffer ready to use.
type Buffer struct {
buf []byte // contents are the bytes buf[off : len(buf)]
off int // read at &buf[off], write at &buf[len(buf)]
bootstrap [64]byte // memory to hold first slice; helps small buffers avoid allocation.
lastRead readOp // last read operation, so that Unread* can work correctly.
}
// Write appends the contents of p to the buffer, growing the buffer as
// needed. The return value n is the length of p; err is always nil. If the
// buffer becomes too large, Write will panic with ErrTooLarge.
func (b *Buffer) Write(p []byte) (n int, err error) {
b.lastRead = opInvalid
m := b.grow(len(p))
return copy(b.buf[m:], p), nil
}
// Read reads the next len(p) bytes from the buffer or until the buffer
// is drained. The return value n is the number of bytes read. If the
// buffer has no data to return, err is io.EOF (unless len(p) is zero);
// otherwise it is nil.
func (b *Buffer) Read(p []byte) (n int, err error) {
b.lastRead = opInvalid
if b.off >= len(b.buf) {
// Buffer is empty, reset to recover space.
b.Truncate(0)
if len(p) == 0 {
return
}
return 0, io.EOF
}
n = copy(p, b.buf[b.off:])
b.off += n
if n > 0 {
b.lastRead = opRead
}
return
}
源碼對于Buffer的定義中,并沒有關于鎖的字段,在write和read函數(shù)中也未發(fā)現(xiàn)鎖的蹤影,所以符合上面提到的文檔中的rule,即Buffer并發(fā)是不安全的赔桌。
如何自定義實現(xiàn)一個并發(fā)安全的Buffer
type Buffer struct {
b bytes.Buffer
rw sync.RWMutex
}
func (b *Buffer) Read(p []byte) (n int, err error) {
b.rw.RLock()
defer b.rw.RUnlock()
return b.b.Read(p)
}
func (b *Buffer) Write(p []byte) (n int, err error) {
b.rw.Lock()
defer b.rw.Unlock()
return b.b.Write(p)
}
通過讀寫鎖,解決并發(fā)讀寫問題,以上提供了Read和Write函數(shù),親,是不是Golang代碼簡潔明了?其它函數(shù)可以在Golang關于Buffer源碼的基礎上自行實現(xiàn)
兩種鎖的區(qū)別
sync.Mutex(互斥鎖) | sync.RWMutex(讀寫鎖) |
---|---|
當一個goroutine訪問的時候供炎,其他goroutine都不能訪問渴逻,保證了資源的同步,避免了競爭音诫,不過也降低了性能 | 非寫狀態(tài)時:多個Goroutine可以同時讀,一個Goroutine寫的時候,其它Goroutine不能讀也不能寫,性能好 |