Go中可以使用“+”合并字符串构回,但是這種合并方式效率非常低猜拾,每合并一次,都是創(chuàng)建一個(gè)新的字符串,就必須遍歷復(fù)制一次字符串拓瞪。Java中提供StringBuilder類(最高效,線程不安全)來解決這個(gè)問題官份。Go中也有類似的機(jī)制只厘,那就是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來組裝字符串,不需要復(fù)制羔味,只需要將添加的字符串放在緩存末尾即可河咽。
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文檔遵循一個(gè)簡(jiǎn)單的規(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
}
源碼對(duì)于Buffer的定義中,并沒有關(guān)于鎖的字段,在write和read函數(shù)中也未發(fā)現(xiàn)鎖的蹤影,所以符合上面提到的文檔中的rule,即Buffer并發(fā)是不安全的忘蟹。
如何自定義實(shí)現(xiàn)一個(gè)并發(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代碼簡(jiǎn)潔明了?其它函數(shù)可以在Golang關(guān)于Buffer源碼的基礎(chǔ)上自行實(shí)現(xiàn)
兩種鎖的區(qū)別
sync.Mutex(互斥鎖) | sync.RWMutex(讀寫鎖) |
---|---|
當(dāng)一個(gè)goroutine訪問的時(shí)候,其他goroutine都不能訪問们陆,保證了資源的同步寒瓦,避免了競(jìng)爭(zhēng),不過也降低了性能 | 非寫狀態(tài)時(shí):多個(gè)Goroutine可以同時(shí)讀,一個(gè)Goroutine寫的時(shí)候,其它Goroutine不能讀也不能寫,性能好 |