本文整理匯總了Golang中sync.Pool.Get方法的典型用法代碼示例。如果您正苦於以下問題:Golang Pool.Get方法的具體用法?Golang Pool.Get怎麽用?Golang Pool.Get使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sync.Pool
的用法示例。
在下文中一共展示了Pool.Get方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: 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)
}
}
示例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: 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()
}
示例4: NewByteArraySize
func NewByteArraySize(pool *sync.Pool, size int) []byte {
if v := pool.Get(); v != nil {
ba := v.([]byte)
return ba
}
return make([]byte, size)
}
示例5: 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)
}
}
示例6: 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
}
示例7: 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
}
}
}
示例8: 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)
}
示例9: 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)
}
示例10: 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)
}
}
示例11: 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)
}
}
示例12: 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
}
示例13: 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())
}
示例14: main
func main() {
var rp sync.Pool
var wp sync.Pool
for i := 0; i < 1024; i++ {
rb := new([]byte)
*rb = make([]byte, 2048)
rp.Put(rb)
}
var counter uint32
log.Fatal(nsk.ListenAndServe(":8000", func(conn *net.TCPConn) {
var s string
var c uint32
var rb *[]byte
var w *bufio.Writer
if v := wp.Get(); v != nil {
w = v.(*bufio.Writer)
w.Reset(conn)
} else {
w = bufio.NewWriter(conn)
}
if v := rp.Get(); v != nil {
rb = v.(*[]byte)
} else {
rb = new([]byte)
*rb = make([]byte, 2048)
}
n, err := conn.Read(*rb)
if err != nil || n <= 0 {
goto E
}
c = atomic.AddUint32(&counter, 1)
s = strconv.FormatUint(uint64(c), 10)
w.WriteString("HTTP/1.1 200 OK\r\n")
w.WriteString("Connection: close\r\n")
w.WriteString(fmt.Sprintf("Content-Length: %d\r\n\r\n", len(s)))
w.WriteString(s)
w.Flush()
E:
conn.Close()
rp.Put(rb)
wp.Put(w)
}))
}
示例15: 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)
}
})
}