1 Star 4 Fork 0

magicianlyx/GoTask

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
queue.go 963 Bytes
一键复制 编辑 原始数据 按行查看 历史
lrf123456 提交于 2019-08-20 15:10 . 抽象队列数据结构
package structure
import (
"sync"
)
type Queue struct {
l sync.RWMutex
list []interface{}
size int
}
func NewQueue(size int) *Queue {
if size <= 0 {
size = 10
}
return &Queue{
l: sync.RWMutex{},
list: make([]interface{}, size),
size: size,
}
}
func (q *Queue) Push(v ...interface{}) {
q.l.Lock()
defer q.l.Unlock()
if len(q.list) >= q.size {
q.list = q.list[1:]
}
q.list = append(q.list, v)
}
func (q *Queue) Pop() interface{} {
q.l.Lock()
defer q.l.Unlock()
if len(q.list) >= 1 {
o := q.list[0]
q.list = q.list[1:]
return o
} else {
return nil
}
}
func (q *Queue) Peek() interface{} {
q.l.RLock()
defer q.l.RUnlock()
if len(q.list) >= 1 {
return q.list[0]
} else {
return nil
}
}
func (q *Queue) Clone() *Queue {
list := make([]interface{}, q.size)
q.l.RLock()
for i := range q.list {
list[i] = q.list[i]
}
q.l.RUnlock()
return &Queue{
l: sync.RWMutex{},
list: list,
size: q.size,
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/magicianlyx/GoTask.git
git@gitee.com:magicianlyx/GoTask.git
magicianlyx
GoTask
GoTask
v1.0.15

搜索帮助

D67c1975 1850385 1daf7b77 1850385