feedback/internal/controller/feedback_queue.go
2023-04-20 07:03:21 +05:00

59 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package controller
import (
"container/list"
"penahub.gitlab.yandexcloud.net/backend/templategen_feedback/internal/models"
"sync"
)
const QueueSize = 100 // Размер очереди
// FeedbackQueue - FIFO очередь с размером QueueSize
type FeedbackQueue struct {
tasks *list.List
m sync.Mutex
}
// NewFeedbackQueue - создать новую очередь
func NewFeedbackQueue() *FeedbackQueue {
return &FeedbackQueue{tasks: list.New(), m: sync.Mutex{}}
}
// Enqueue - добавить элемент в очередь. Возвращает true если очередь не переполнена и false в ином случае
func (q *FeedbackQueue) Enqueue(record *models.Feedback) bool {
q.m.Lock()
if q.tasks.Len() >= QueueSize {
q.m.Unlock()
return false
}
q.tasks.PushBack(record)
q.m.Unlock()
return true
}
// Dequeue - взять элемент из очереди
func (q *FeedbackQueue) Dequeue() *models.Feedback {
q.m.Lock()
value := q.tasks.Front()
if value == nil {
q.m.Unlock()
return nil
}
q.tasks.Remove(value)
q.m.Unlock()
return value.Value.(*models.Feedback)
}
// Len - получить длину очереди
func (q *FeedbackQueue) Len() int {
q.m.Lock()
l := q.tasks.Len()
q.m.Unlock()
return l
}