本文整理匯總了Golang中sync.Pool類的典型用法代碼示例。如果您正苦於以下問題:Golang Pool類的具體用法?Golang Pool怎麽用?Golang Pool使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Pool類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: 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)
}
}
示例2: 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
}
示例3: main
func main() {
_, err := OutFunc()
if err != nil {
log.Printf("error is : %v", err)
}
fmt.Printf("End of main")
data := []int{0, 1, 2, 3, 4}
s1 := data[:2]
fmt.Printf("data ptr is %p, s1 ptr is %p", &data, &s1)
s2 := append(s1, 100, 200)
fmt.Println("\n", data)
fmt.Println(s1)
fmt.Println(s2)
fmt.Printf("data ptr is %p, s1 ptr is %p, s2 ptr is %p \n", &data, &s1, &s2)
var pool *sync.Pool
pool = new(sync.Pool)
pool.New = func() interface{} {
return 1
}
//pool.Put(1)
i := pool.Get()
if i == nil {
fmt.Println("pool.Get is non-block function. nil could be returned. not cool")
} else {
fmt.Println("number is ", i)
}
}
示例4: 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()
}
示例5: NewByteArraySize
func NewByteArraySize(pool *sync.Pool, size int) []byte {
if v := pool.Get(); v != nil {
ba := v.([]byte)
return ba
}
return make([]byte, size)
}
示例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: newBufferPool
func newBufferPool() *bufferPool {
var p sync.Pool
p.New = func() interface{} {
return make([]byte, 20480)
}
return &bufferPool{p}
}
示例8: NewByteSlicePool
func NewByteSlicePool(size int) *ByteSlicePool {
p := new(sync.Pool)
p.New = func() interface{} {
return make([]byte, size)
}
return &ByteSlicePool{p}
}
示例9: NewBufioReaderSize
// TODO
func NewBufioReaderSize(pool *sync.Pool, r io.Reader, size int) *bufio.Reader {
if v := pool.Get(); v != nil {
br := v.(*bufio.Reader)
br.Reset(r)
return br
}
return bufio.NewReaderSize(r, size)
}
示例10: NewBufioWriterSize
func NewBufioWriterSize(pool *sync.Pool, w io.Writer, size int) *bufio.Writer {
if v := pool.Get(); v != nil {
bw := v.(*bufio.Writer)
bw.Reset(w)
return bw
}
return bufio.NewWriterSize(w, size)
}
示例11: 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)
}
}
示例12: 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)
}
}
示例13: newWriterLevel
func newWriterLevel(pool *sync.Pool, w io.Writer, level int) *gzip.Writer {
if v := pool.Get(); v != nil {
zw := v.(*gzip.Writer)
zw.Reset(w)
return zw
}
zw, _ := gzip.NewWriterLevel(w, level)
return zw
}
示例14: NewMPool
func NewMPool(sz int) *MPool {
p := &MPool{sz: sz}
pool := new(sync.Pool)
pool.New = func() interface{} {
buf := make([]byte, p.sz)
atomic.AddInt32(&p.alloced, 1)
return buf
}
p.pool = pool
return p
}
示例15: 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)
}