本文整理匯總了Golang中sync.Pool.Put方法的典型用法代碼示例。如果您正苦於以下問題:Golang Pool.Put方法的具體用法?Golang Pool.Put怎麽用?Golang Pool.Put使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sync.Pool
的用法示例。
在下文中一共展示了Pool.Put方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: dine
func (p person) dine(wg *sync.WaitGroup, foodPool *sync.Pool) {
for {
if !foodRemains() {
break
}
potentialDish := foodPool.Get()
if potentialDish == nil {
fmt.Printf("%s recieved a nil dish\n", p.Name)
break
}
someDish, ok := potentialDish.(dish)
if !ok {
fmt.Printf("%s was unable to turn a potential dish into a real dish\n", p.Name)
continue
}
p.consume(&someDish)
if someDish.Bites <= 0 {
fmt.Printf("%s finished %s\n", p.Name, someDish.Name)
} else {
foodPool.Put(someDish)
}
}
wg.Done()
}
示例2: Gzip
func Gzip(level int) gin.HandlerFunc {
var gzPool sync.Pool
gzPool.New = func() interface{} {
gz, err := gzip.NewWriterLevel(ioutil.Discard, level)
if err != nil {
panic(err)
}
return gz
}
return func(c *gin.Context) {
if !shouldCompress(c.Request) {
return
}
gz := gzPool.Get().(*gzip.Writer)
defer gzPool.Put(gz)
gz.Reset(c.Writer)
c.Header("Content-Encoding", "gzip")
c.Header("Vary", "Accept-Encoding")
c.Writer = &gzipWriter{c.Writer, gz}
defer func() {
c.Header("Content-Length", "0")
gz.Close()
}()
c.Next()
}
}
示例3: main
func main() {
// 禁用GC,並保證在main函數執行結束前恢複GC
defer debug.SetGCPercent(debug.SetGCPercent(-1))
var count int32
newFunc := func() interface{} {
return atomic.AddInt32(&count, 1)
}
pool := sync.Pool{New: newFunc}
// New 字段值的作用
v1 := pool.Get()
fmt.Printf("v1: %v\n", v1)
// 臨時對象池的存取
pool.Put(newFunc())
pool.Put(newFunc())
pool.Put(newFunc())
v2 := pool.Get()
fmt.Printf("v2: %v\n", v2)
// 垃圾回收對臨時對象池的影響
debug.SetGCPercent(100)
runtime.GC()
v3 := pool.Get()
fmt.Printf("v3: %v\n", v3)
pool.New = nil
v4 := pool.Get()
fmt.Printf("v4: %v\n", v4)
}
示例4: ReadSocket
func (s *Server) ReadSocket(packetPool *sync.Pool) {
// each goroutine gets its own socket
// if the sockets support SO_REUSEPORT, then this will cause the
// kernel to distribute datagrams across them, for better read
// performance
s.logger.WithField("address", s.UDPAddr).Info("UDP server listening")
serverConn, err := NewSocket(s.UDPAddr, s.RcvbufBytes)
if err != nil {
// if any goroutine fails to create the socket, we can't really
// recover, so we just blow up
// this probably indicates a systemic issue, eg lack of
// SO_REUSEPORT support
s.logger.WithError(err).Fatal("Error listening for UDP")
}
for {
buf := packetPool.Get().([]byte)
n, _, err := serverConn.ReadFrom(buf)
if err != nil {
s.logger.WithError(err).Error("Error reading from UDP")
continue
}
s.HandlePacket(buf[:n])
// the Metric struct created by HandlePacket has no byte slices in it,
// only strings
// therefore there are no outstanding references to this byte slice, we
// can return it to the pool
packetPool.Put(buf)
}
}
示例5: ExampleNumberPool_1
// Example use of a pool to manage a free list of numbers
func ExampleNumberPool_1() {
// Create a Context
ctx := dec.NewContext(dec.InitDecimal128, 0)
// New() function for the pool to create new numbers
newFunc := func() interface{} { return dec.NewNumber(ctx.Digits()) }
// create a pool. Either dec.Pool or sync.Pool will do
syncPool := sync.Pool{New: newFunc}
// We can use Get().(*dec.Number) to get new or reusable numbers
number := syncPool.Get().(*dec.Number)
fmt.Printf("from sync.Pool: %s\n", number.Zero())
// We're done with it, put it back in the pool
syncPool.Put(number)
// Or, wrap it with a NumberPool so that Get() returns *Number instead of interface{}.
// NumberPool also helps keeping track of the context.
pool := &dec.NumberPool{&syncPool, ctx}
// and benefit: no need to type-cast
number = pool.Get()
// Introducing the idiomatic code: defer Put() the *Number right after Get()
defer pool.Put(number)
fmt.Printf("from sync.Pool: %s\n", number.FromString("1243", pool.Context))
// Output:
// from sync.Pool: 0
// from sync.Pool: 1243
}
示例6: Middleware
// Middleware encodes the response using Gzip encoding and sets all the appropriate
// headers. If the Content-Type is not set, it will be set by calling
// http.DetectContentType on the data being written.
func Middleware(level int) goa.Middleware {
gzipPool := sync.Pool{
New: func() interface{} {
gz, err := gzip.NewWriterLevel(ioutil.Discard, level)
if err != nil {
panic(err)
}
return gz
},
}
return func(h goa.Handler) goa.Handler {
return func(ctx *goa.Context) (err error) {
r := ctx.Request()
// Skip compression if the client doesn't accept gzip encoding, is
// requesting a WebSocket or the data is already compressed.
if !strings.Contains(r.Header.Get(headerAcceptEncoding), encodingGzip) ||
len(r.Header.Get(headerSecWebSocketKey)) > 0 ||
ctx.Header().Get(headerContentEncoding) == encodingGzip {
return h(ctx)
}
// Set the appropriate gzip headers.
ctx.Header().Set(headerContentEncoding, encodingGzip)
ctx.Header().Set(headerVary, headerAcceptEncoding)
// Retrieve gzip writer from the pool. Reset it to use the ResponseWriter.
// This allows us to re-use an already allocated buffer rather than
// allocating a new buffer for every request.
gz := gzipPool.Get().(*gzip.Writer)
// Get the original http.ResponseWriter
w := ctx.SetResponseWriter(nil)
// Reset our gzip writer to use the http.ResponseWriter
gz.Reset(w)
// Wrap the original http.ResponseWriter with our gzipResponseWriter
grw := gzipResponseWriter{
ResponseWriter: w,
gzw: gz,
}
// Set the new http.ResponseWriter
ctx.SetResponseWriter(grw)
// Call the next handler supplying the gzipResponseWriter instead of
// the original.
err = h(ctx)
if err != nil {
return
}
// Delete the content length after we know we have been written to.
grw.Header().Del(headerContentLength)
gz.Close()
gzipPool.Put(gz)
return
}
}
}
示例7: BenchmarkAllocSyncPool
func BenchmarkAllocSyncPool(b *testing.B) {
var p sync.Pool
s := make([]byte, 10)
for i := 0; i < b.N; i++ {
p.Put(s)
s = p.Get().([]byte)
}
}
示例8: BenchmarkRuntimeCallersSyncPool
func BenchmarkRuntimeCallersSyncPool(b *testing.B) {
pool := sync.Pool{New: func() interface{} { return make([]uintptr, 32) }}
for i := 0; i < b.N; i++ {
pcs := pool.Get().([]uintptr)
runtime.Callers(0, pcs[:])
pcs = pcs[0:]
pool.Put(pcs)
}
}
示例9: releasePipelineWork
func releasePipelineWork(pool *sync.Pool, w *pipelineWork) {
if w.t != nil {
w.t.Stop()
}
w.reqCopy.Reset()
w.respCopy.Reset()
w.req = nil
w.resp = nil
w.err = nil
pool.Put(w)
}
示例10: main
func main() {
var pool sync.Pool
var a = 1
pool.Put(a)
pool.Put(new(User))
fmt.Println(pool.Get())
runtime.GC()
fmt.Println(pool.Get())
fmt.Println(pool.Get())
}
示例11: benchPool
func benchPool(i int, b *testing.B) {
pool := sync.Pool{New: func() interface{} {
return make([]int, 0, i)
}}
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
s := pool.Get().([]int)[:0]
pool.Put(s)
}
})
}
示例12: BenchmarkAllocSyncPool
func BenchmarkAllocSyncPool(b *testing.B) {
var p sync.Pool
s := make([]byte, 10)
for i := 0; i < b.N; i++ {
p.Put(s)
si := p.Get()
var ok bool
s, ok = si.([]byte)
if !ok {
s = make([]byte, 10)
}
}
}
示例13: callServer
func callServer(clientPool *sync.Pool, s rpcx.ClientSelector) {
client := clientPool.Get().(*rpcx.Client)
args := &Args{7, 8}
var reply Reply
err := client.Call("Arith.Mul", args, &reply)
if err != nil {
fmt.Printf("error for Arith: %d*%d, %v \n", args.A, args.B, err)
} else {
fmt.Printf("Arith: %d*%d=%d, client: %p \n", args.A, args.B, reply.C, client)
}
clientPool.Put(client)
}
示例14: main
func main() {
var pool sync.Pool
pool.New = func() interface{} {
return person{name: "name", timestamp: time.Now()}
}
var p, q, r person
p = pool.Get().(person)
fmt.Println(p.timestamp.String())
pool.Put(p)
r = pool.Get().(person)
q = pool.Get().(person)
fmt.Println(r.timestamp.String())
fmt.Println(q.timestamp.String())
}
示例15: CreateRegistrator
func (s *Server) CreateRegistrator(username, password string) *Registrator {
pool := sync.Pool{New: func() interface{} { return new(string) }}
for i := 1000; i < 9999; i++ {
pool.Put(strconv.Itoa(i))
}
registrator := &Registrator{
Login: username,
Password: password,
MsgChan: make(chan interface{}),
Server: s,
Queue: make(map[string]*QueueMember),
GroupManager: &GroupManager{Requests: make(map[string]interface{})},
UniqueCodes: &pool,
}
return registrator
}