Esempio n. 1
0
func grabBufferAndUseIt(pool gopool.Pool) error {
	// WARNING: Must ensure resource returns to pool otherwise gopool will deadlock once all
	// resources used.
	bb := pool.Get().(*bytes.Buffer)
	defer pool.Put(bb) // IMPORTANT: defer here to ensure invoked even when subsequent code bails

	for k := 0; k < bufSize; k++ {
		if rand.Intn(100000000) == 1 {
			return errors.New("random error to illustrate need to return resource to pool")
		}
		bb.WriteByte(byte(k % 256))
	}
	return nil
}
Esempio n. 2
0
func testC(bp gopool.Pool, concurrency, loops int) {
	const byteCount = defaultBufSize / 2

	var wg sync.WaitGroup
	wg.Add(concurrency)
	for c := 0; c < concurrency; c++ {
		go func() {
			for j := 0; j < loops; j++ {
				bb := bp.Get().(*bytes.Buffer)
				max := byteCount
				if j%8 == 0 {
					max = 2 * defaultMaxKeep
				}
				for k := 0; k < max; k++ {
					bb.WriteByte(byte(k % 256))
				}
				bp.Put(bb)
			}
			wg.Done()
		}()
	}
	wg.Wait()
}