gitee.com/quant1x/gox@v1.21.2/coroutine/channel.go (about) 1 package coroutine 2 3 import ( 4 "sync" 5 "sync/atomic" 6 ) 7 8 // Channel 多协程安全的channel 9 type Channel[E any] struct { 10 data chan E 11 m sync.Mutex 12 num atomic.Int64 13 done atomic.Uint32 14 } 15 16 func (c *Channel[E]) Push(v E) { 17 if c.done.Load() == 1 { 18 return 19 } 20 c.data <- v 21 c.num.Add(1) 22 } 23 24 func (c *Channel[E]) Pop() E { 25 v := <-c.data 26 c.num.Add(-1) 27 return v 28 } 29 30 func (c *Channel[E]) Close() { 31 if c.done.Load() != 0 { 32 return 33 } 34 c.m.Lock() 35 defer c.m.Unlock() 36 if c.done.Load() == 0 { 37 c.done.Store(1) 38 } 39 }