golang sync.Pool 指針數(shù)據(jù)覆蓋問題解決
場(chǎng)景
1. sync.Pool設(shè)置
var stringPool = sync.Pool{
New: func() any {
return new([]string)
},
}
func NewString() *[]string {
v := stringPool.Get().(*[]string)
return v
}
func PutString(s *[]string) {
if s == nil {
return
}
if cap(*s) > 2048 {
s = nil
} else {
*s = (*s)[:0]
stringPool.Put(s)
}
}2.使用sync.Pool
func Test_Pool(t *testing.T) {
dataSlice1 := demoData()
dataSlice2 := demoData()
dataSlice2[1] = "test4"
fmt.Printf("dataSlice1:%v %p,dataSlice2:%v %p\n", dataSlice1, dataSlice1, dataSlice2, dataSlice2)
}
func demoData() []string {
strsPtr := NewString()
strs := *strsPtr
defer func() {
*strsPtr = strs
PutString(strsPtr)
}()
strs = append(strs, "test1", "test2")
return strs
}打印結(jié)果:dataSlice1:[test1 test4] 0xc0000a6400,dataSlice2:[test1 test4] 0xc0000a6400
可以看到兩個(gè)slice地址相同,內(nèi)部使用同一個(gè)地址的數(shù)組,導(dǎo)致兩次獲取的數(shù)據(jù)互相影響
3.解決方法1
func Test_Pool(t *testing.T) {
dataSlice1 := demoData()
dataSlice2 := demoData()
dataSlice2[1] = "test4"
fmt.Printf("dataSlice1:%v %p,dataSlice2:%v %p\n", dataSlice1, dataSlice1, dataSlice2, dataSlice2)
}
func demoData() []string {
strsPtr := NewString()
strs := *strsPtr
defer func() {
*strsPtr = strs
PutString(strsPtr)
}()
strs = append(strs, "test1", "test2")
// 深復(fù)制
var items = make([]string, len(strs))
copy(items, strs)
return items
}使用深復(fù)制,在put回sync.Pool中之前把數(shù)據(jù)復(fù)制返回,但這樣資源池失去了意義,獲取到資源后有進(jìn)行了一次內(nèi)存的申請(qǐng)
4.解決方法2
我們看下golang語(yǔ)言源碼怎么解決的
參考 go/src/fmt/print.go 302行 Fprintln方法
func Fprintln(w io.Writer, a ...any) (n int, err error) {
p := newPrinter()
p.doPrintln(a)
n, err = w.Write(p.buf)
p.free()
return
}可以看到306行有p.free()代碼,newPrinter()和free()之間進(jìn)行數(shù)據(jù)處理,數(shù)據(jù)處理完成之后再把資源返回給sync.Pool
總結(jié)
不是任何場(chǎng)景都適合用sync.Pool,需要關(guān)注并發(fā)情況下資源池中數(shù)據(jù)同步修改影響的問題。
到此這篇關(guān)于golang sync.Pool 指針數(shù)據(jù)覆蓋問題解決的文章就介紹到這了,更多相關(guān)golang sync.Pool 指針覆蓋內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于Go 空結(jié)構(gòu)體的 3 種使用場(chǎng)景
在今天這篇文章要給大家介紹得是Go 語(yǔ)言中幾種常見類型的寬度,并且基于開頭的問題 ”空結(jié)構(gòu)體“ 進(jìn)行了剖析,需要的朋友可以參考一下,希望對(duì)你有所幫助2021-10-10
簡(jiǎn)單談?wù)凣olang中的字符串與字節(jié)數(shù)組
這篇文章主要給大家介紹了關(guān)于Golang中字符串與字節(jié)數(shù)組的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用Golang具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
使用Go語(yǔ)言開發(fā)自動(dòng)化API測(cè)試工具詳解
這篇文章主要為大家詳細(xì)介紹了如何使用Go語(yǔ)言開發(fā)自動(dòng)化API測(cè)試工具,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,有需要的小伙伴可以參考下2024-03-03
GoLang中socket心跳檢測(cè)的實(shí)現(xiàn)
本文主要介紹了GoLang中socket心跳檢測(cè)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-02-02

