当前位置: 首页>>代码示例>>Golang>>正文


Golang sync.Pool类代码示例

本文整理汇总了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)
	}
}
开发者ID:carriercomm,项目名称:veneur,代码行数:30,代码来源:server.go

示例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
}
开发者ID:db47h,项目名称:go-decnumber,代码行数:30,代码来源:example_test.go

示例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)
	}

}
开发者ID:silentred,项目名称:learning-path,代码行数:30,代码来源:testGo.go

示例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()
}
开发者ID:agocs,项目名称:concurrency_examples,代码行数:25,代码来源:tapas_pool.go

示例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)
}
开发者ID:xingskycn,项目名称:goim,代码行数:7,代码来源:bufio.go

示例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
		}
	}
}
开发者ID:jim-slattery-rs,项目名称:middleware,代码行数:62,代码来源:middleware.go

示例7: newBufferPool

func newBufferPool() *bufferPool {
	var p sync.Pool
	p.New = func() interface{} {
		return make([]byte, 20480)
	}

	return &bufferPool{p}
}
开发者ID:codemodus,项目名称:porter,代码行数:8,代码来源:porter.go

示例8: NewByteSlicePool

func NewByteSlicePool(size int) *ByteSlicePool {
	p := new(sync.Pool)
	p.New = func() interface{} {
		return make([]byte, size)
	}

	return &ByteSlicePool{p}
}
开发者ID:Wessie,项目名称:sirencast,代码行数:8,代码来源:pool.go

示例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)
}
开发者ID:xingskycn,项目名称:goim,代码行数:9,代码来源:bufio.go

示例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)
}
开发者ID:xingskycn,项目名称:goim,代码行数:8,代码来源:bufio.go

示例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)
	}
}
开发者ID:jmptrader,项目名称:gohacks,代码行数:8,代码来源:pool_test.go

示例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)
	}
}
开发者ID:chrisp-fb,项目名称:rell,代码行数:9,代码来源:bench_test.go

示例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
}
开发者ID:bsm,项目名称:gziphandler,代码行数:9,代码来源:gzip.go

示例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
}
开发者ID:kevin1sMe,项目名称:gotunnel,代码行数:11,代码来源:mpool.go

示例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)
}
开发者ID:eurie-inc,项目名称:echo-sample,代码行数:11,代码来源:client.go


注:本文中的sync.Pool类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。