This repository has been archived on 2024-07-22. You can view files and clone it, but cannot push or open issues or pull requests.
e621-sdk-go/utils/queue.go

45 lines
1.1 KiB
Go
Raw Normal View History

package utils
import (
"errors"
log "github.com/sirupsen/logrus"
)
type Queue struct {
tasks []SchedulerTask
notifyChannel chan bool
}
func NewQueue() Queue {
return Queue{
notifyChannel: make(chan bool),
}
}
// WaitForElement need to be called everytime before Popping an Element!
// Also, it is required to have this function called in a separate go-routine because Push use the NotifyChannel in the
// routine. So the thread waits, till WaitForElement pulls the Item from the channel
// FIXME this should be fixed in future. require more discussion what is the best way.
func (queue *Queue) WaitForElement() {
log.Debug("waiting for element")
_ = <-queue.notifyChannel
}
func (queue *Queue) Pop() (SchedulerTask, error) {
if len(queue.tasks) == 0 {
return nil, errors.New("try to remove an element of a empty queue")
}
task := queue.tasks[0]
queue.tasks = queue.tasks[1:]
return task, nil
}
func (queue *Queue) Push(task SchedulerTask) error {
if task == nil {
return errors.New("try to add task but task is empty")
}
queue.tasks = append(queue.tasks, task)
queue.notifyChannel <- true
return nil
}