pool.mx raw

   1  package sync
   2  
   3  import "internal/task"
   4  
   5  // Pool is a very simple implementation of sync.Pool.
   6  type Pool struct {
   7  	lock  task.PMutex
   8  	New   func() interface{}
   9  	items []interface{}
  10  }
  11  
  12  // Get returns an item in the pool, or the value of calling Pool.New() if there are no items.
  13  func (p *Pool) Get() interface{} {
  14  	p.lock.Lock()
  15  	if len(p.items) > 0 {
  16  		x := p.items[len(p.items)-1]
  17  		p.items = p.items[:len(p.items)-1]
  18  		p.lock.Unlock()
  19  		return x
  20  	}
  21  	p.lock.Unlock()
  22  	if p.New == nil {
  23  		return nil
  24  	}
  25  	return p.New()
  26  }
  27  
  28  // Put adds a value back into the pool.
  29  func (p *Pool) Put(x interface{}) {
  30  	p.lock.Lock()
  31  	p.items = append(p.items, x)
  32  	p.lock.Unlock()
  33  }
  34