github.com/gopherjs/gopherjs@v1.19.0-beta1.0.20240506212314-27071a8796e4/compiler/natives/src/sync/pool.go (about)

     1  //go:build js
     2  // +build js
     3  
     4  package sync
     5  
     6  // A Pool is a set of temporary objects that may be individually saved and
     7  // retrieved.
     8  //
     9  // GopherJS provides a simpler, naive implementation with no synchronization at
    10  // all. This is still correct for the GopherJS runtime because:
    11  //
    12  //  1. JavaScript is single-threaded, so it is impossible for two threads to be
    13  //     accessing the pool at the same moment in time.
    14  //  2. GopherJS goroutine implementation uses cooperative multi-tasking model,
    15  //     which only allows passing control to other goroutines when the function
    16  //     might block.
    17  //
    18  // TODO(nevkontakte): Consider adding a mutex just to be safe if it doesn't
    19  // create a large performance hit.
    20  //
    21  // Note: there is a special handling in the gopherjs/build package that filters
    22  // out all original Pool implementation in order to avoid awkward unused fields
    23  // referenced by dead code.
    24  type Pool struct {
    25  	store []interface{}
    26  	New   func() interface{}
    27  }
    28  
    29  func (p *Pool) Get() interface{} {
    30  	if len(p.store) == 0 {
    31  		if p.New != nil {
    32  			return p.New()
    33  		}
    34  		return nil
    35  	}
    36  	x := p.store[len(p.store)-1]
    37  	p.store = p.store[:len(p.store)-1]
    38  	return x
    39  }
    40  
    41  func (p *Pool) Put(x interface{}) {
    42  	if x == nil {
    43  		return
    44  	}
    45  	p.store = append(p.store, x)
    46  }
    47  
    48  // These are referenced by tests, but are no-ops in GopherJS runtime.
    49  func runtime_procPin() int { return 0 }
    50  func runtime_procUnpin()   {}