2019-02-02 16:18:25 +08:00
|
|
|
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
2018-02-02 16:56:53 +08:00
|
|
|
//
|
|
|
|
// 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,
|
2019-02-02 16:18:25 +08:00
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
2018-02-02 16:56:53 +08:00
|
|
|
|
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操作.
|
2018-02-02 16:56:53 +08:00
|
|
|
package gchan
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2019-02-02 16:18:25 +08:00
|
|
|
"github.com/gogf/gf/g/container/gtype"
|
2018-02-02 16:56:53 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type Chan struct {
|
|
|
|
list chan interface{}
|
2018-03-29 13:46:05 +08:00
|
|
|
closed *gtype.Bool
|
2018-02-02 16:56:53 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func New(limit int) *Chan {
|
|
|
|
return &Chan {
|
2018-03-29 13:46:05 +08:00
|
|
|
list : make(chan interface{}, limit),
|
|
|
|
closed : gtype.NewBool(),
|
2018-02-02 16:56:53 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 将数据压入队列
|
|
|
|
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")
|
2018-02-02 16:56:53 +08:00
|
|
|
}
|
|
|
|
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) {
|
2018-02-02 16:56:53 +08:00
|
|
|
close(q.list)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 获取当前队列大小
|
|
|
|
func (q *Chan) Size() int {
|
|
|
|
return len(q.list)
|
|
|
|
}
|