github.com/haraldrudell/parl@v0.4.176/lazy-chan.go (about)

     1  /*
     2  © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package parl
     7  
     8  import "sync/atomic"
     9  
    10  type LacyChan[T any] struct{ cp atomic.Pointer[chan T] }
    11  
    12  func (c *LacyChan[T]) Get(n ...int) (ch chan T) {
    13  	if chp := c.cp.Load(); chp != nil {
    14  		ch = *chp
    15  		return
    16  	}
    17  	var n0 int
    18  	if len(n) > 0 && n[0] >= 0 {
    19  		n0 = n[0]
    20  	}
    21  	ch = make(chan T, n0)
    22  	if c.cp.CompareAndSwap(nil, &ch) {
    23  		return
    24  	}
    25  	ch = *c.cp.Load()
    26  	return
    27  }