taskExecute/mq/queue.go

78 lines
1.5 KiB
Go
Raw Normal View History

2023-03-23 14:35:24 +08:00
package mq
import "fmt"
type WorkflowQueue struct {
buff []string //队列的的数据存储在数组上
maxsize int //队列最大容量
front int //队列头索引,不包括自己(队列头索引值-1
rear int //队列尾索引
}
func NewQueue(size int) *WorkflowQueue {
return &WorkflowQueue{
buff: make([]string, 0, size),
maxsize: 5,
front: -1,
rear: -1,
}
}
// Push
// @Description: 压入队列
// @Author: maxwell.ke
// @time 2022-10-25 22:58:58
// @receiver q
// @param n
// @return error
func (q *WorkflowQueue) Push(id string) error {
if q.rear == q.maxsize-1 {
if q.front == -1 { //头尾都到头了
return fmt.Errorf("队列已满PUSH失败")
} else {
q.front = -1
q.rear = len(q.buff) - 1
}
}
q.rear++
q.buff = append(q.buff, id)
return nil
}
// Pop
// @Description: 出队列
// @Author: maxwell.ke
// @time 2022-10-25 23:14:20
// @receiver q
// @return n
// @return err
func (q *WorkflowQueue) Pop() (id string, err error) {
if len(q.buff) == 0 {
return "", fmt.Errorf("空队列,POP失败")
}
id = q.buff[0]
q.buff = q.buff[1:]
q.front++
return id, nil
}
// List
// @Description: 队列遍历
// @Author: maxwell.ke
// @time 2022-10-25 23:13:10
// @receiver q
// @return error
func (q *WorkflowQueue) List() error {
if len(q.buff) == 0 {
return fmt.Errorf("空队列")
}
for i := 0; i < q.maxsize; i++ {
if i > q.front && i <= q.rear {
fmt.Println(q.buff[i-q.front-1])
} else {
return fmt.Errorf("空队列")
}
}
return nil
}