GO語言"sync"包中"Pool"類型的用法及代碼示例。
池是一組可以單獨保存和檢索的臨時對象。
存儲在池中的任何項目都可能隨時自動刪除,恕不另行通知。如果在發生這種情況時 Pool 擁有唯一的引用,則該項目可能會被釋放。
一個 Pool 可以安全地同時被多個 goroutine 使用。
Pool 的目的是緩存已分配但未使用的項目以供以後重用,減輕垃圾Collector的壓力。也就是說,它使構建高效、線程安全的空閑列表變得容易。但是,它並不適用於所有空閑列表。
Pool 的適當用途是管理一組在包的並發獨立客戶端之間靜默共享並可能被重用的臨時項目。 Pool 提供了一種在許多客戶端之間分攤分配開銷的方法。
一個很好地使用池的例子是在 fmt 包中,它維護一個動態大小的臨時輸出緩衝區存儲。存儲在負載下擴展(當許多 goroutine 正在積極打印時)並在靜止時縮小。
另一方麵,作為short-lived 對象的一部分維護的空閑列表不適合用於池,因為在這種情況下開銷不能很好地攤銷。讓這些對象實現它們自己的空閑列表更有效。
首次使用後不得複製池。
用法:
type Pool struct {
// New optionally specifies a function to generate
// a value when Get would otherwise return nil.
// It may not be changed concurrently with calls to Get.
New func() any
// contains filtered or unexported fields
}
例子:
package main
import (
"bytes"
"io"
"os"
"sync"
"time"
)
var bufPool = sync.Pool{
New: func() any {
// The Pool's New function should generally only return pointer
// types, since a pointer can be put into the return interface
// value without an allocation:
return new(bytes.Buffer)
},
}
// timeNow is a fake version of time.Now for tests.
func timeNow() time.Time {
return time.Unix(1136214245, 0)
}
func Log(w io.Writer, key, val string) {
b := bufPool.Get().(*bytes.Buffer)
b.Reset()
// Replace this with time.Now() in a real logger.
b.WriteString(timeNow().UTC().Format(time.RFC3339))
b.WriteByte(' ')
b.WriteString(key)
b.WriteByte('=')
b.WriteString(val)
w.Write(b.Bytes())
bufPool.Put(b)
}
func main() {
Log(os.Stdout, "path", "/search?q=flowers")
}
輸出:
2006-01-02T15:04:05Z path=/search?q=flowers
相關用法
- GO Pow10用法及代碼示例
- GO Polar用法及代碼示例
- GO Pow用法及代碼示例
- GO PutUvarint用法及代碼示例
- GO ParseAddress用法及代碼示例
- GO PlainAuth用法及代碼示例
- GO Print用法及代碼示例
- GO ParseUint用法及代碼示例
- GO ParseIP用法及代碼示例
- GO Printf用法及代碼示例
- GO ParseMediaType用法及代碼示例
- GO ParseInt用法及代碼示例
- GO ParseCIDR用法及代碼示例
- GO PutVarint用法及代碼示例
- GO Perm用法及代碼示例
- GO Pipe用法及代碼示例
- GO ParseInLocation用法及代碼示例
- GO PathUnescape用法及代碼示例
- GO ParseDuration用法及代碼示例
- GO ParseFile用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Pool。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。