gf/g/container/gchan/gchan.go

53 lines
1.2 KiB
Go
Raw Normal View History

// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
2019-01-15 23:27:47 +08:00
// Package gchan provides graceful operations for channel.
2019-01-16 13:35:16 +08:00
//
2019-01-15 23:27:47 +08:00
// 优雅的Channel操作.
package gchan
import (
"errors"
"github.com/gogf/gf/g/container/gtype"
)
type Chan struct {
list chan interface{}
2018-03-29 13:46:05 +08:00
closed *gtype.Bool
}
func New(limit int) *Chan {
return &Chan {
2018-03-29 13:46:05 +08:00
list : make(chan interface{}, limit),
closed : gtype.NewBool(),
}
}
// 将数据压入队列
func (q *Chan) Push(v interface{}) error {
2018-03-29 13:46:05 +08:00
if q.closed.Val() {
2018-02-07 09:42:18 +08:00
return errors.New("closed")
}
q.list <- v
return nil
}
// 先进先出地从队列取出一项数据,当没有数据可获取时,阻塞等待
func (q *Chan) Pop() interface{} {
return <- q.list
}
// 关闭队列(通知所有通过Pop阻塞的协程退出)
func (q *Chan) Close() {
2018-11-18 22:22:44 +08:00
if !q.closed.Set(true) {
close(q.list)
}
}
// 获取当前队列大小
func (q *Chan) Size() int {
return len(q.list)
}