2 Star 2 Fork 8

王布衣/gox

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
channel.go 1.15 KB
一键复制 编辑 原始数据 按行查看 历史
package coroutine
import (
"errors"
"sync"
"sync/atomic"
"time"
)
var (
ErrChannelClosed = errors.New("channel closed")
ErrBufferFull = errors.New("buffer full")
)
type Channel[E any] struct {
data chan E
closeOnce sync.Once
closed atomic.Bool
num atomic.Int64
}
func NewChannel[E any](bufSize int) *Channel[E] {
return &Channel[E]{
data: make(chan E, bufSize),
}
}
func (c *Channel[E]) Push(v E) error {
if c.closed.Load() {
return ErrChannelClosed
}
select {
case c.data <- v:
c.num.Add(1)
return nil
default:
return ErrBufferFull
}
}
// SafePush 带超时的安全推送
func (c *Channel[E]) SafePush(v E, timeout time.Duration) error {
if c.closed.Load() {
return ErrChannelClosed
}
select {
case c.data <- v:
c.num.Add(1)
return nil
case <-time.After(timeout):
return ErrBufferFull
}
}
func (c *Channel[E]) Pop() (E, bool) {
v, ok := <-c.data
if ok {
c.num.Add(-1)
}
return v, ok
}
func (c *Channel[E]) Close() {
c.closeOnce.Do(func() {
close(c.data)
c.closed.Store(true)
})
}
func (c *Channel[E]) Len() int {
return int(c.num.Load())
}
func (c *Channel[E]) Cap() int {
return cap(c.data)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/quant1x/gox.git
git@gitee.com:quant1x/gox.git
quant1x
gox
gox
v1.22.12

搜索帮助