當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Pool.Put方法代碼示例

本文整理匯總了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()
}
開發者ID:agocs,項目名稱:concurrency_examples,代碼行數:25,代碼來源:tapas_pool.go

示例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()
	}
}
開發者ID:gin-contrib,項目名稱:gzip,代碼行數:28,代碼來源:gzip.go

示例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)
}
開發者ID:NONFish,項目名稱:goc2p,代碼行數:29,代碼來源:pool_demo.go

示例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)
	}
}
開發者ID:carriercomm,項目名稱:veneur,代碼行數:30,代碼來源:server.go

示例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
}
開發者ID:db47h,項目名稱:go-decnumber,代碼行數:30,代碼來源:example_test.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: 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

示例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)
	}
}
開發者ID:chrisp-fb,項目名稱:rell,代碼行數:9,代碼來源:bench_test.go

示例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)
}
開發者ID:eurie-inc,項目名稱:echo-sample,代碼行數:11,代碼來源:client.go

示例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())
}
開發者ID:nemowen,項目名稱:golang,代碼行數:12,代碼來源:testPool.go

示例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)
		}
	})
}
開發者ID:WeavingCode,項目名稱:syncthing,代碼行數:12,代碼來源:segments_test.go

示例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)
		}
	}
}
開發者ID:npat-efault,項目名稱:gohacks,代碼行數:13,代碼來源:pool_test.go

示例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)
}
開發者ID:xiongeee,項目名稱:rpcx,代碼行數:14,代碼來源:client.go

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

}
開發者ID:kavehmz,項目名稱:garbage,代碼行數:16,代碼來源:tmp29.go

示例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
}
開發者ID:seka17,項目名稱:bracelet,代碼行數:17,代碼來源:registrator.go


注:本文中的sync.Pool.Put方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。