Lennard Brinkhaus
31bd0cf639
Co-authored-by: Fenpaws <soxx@fenpa.ws> Reviewed-on: anthrove/e621-to-graph#13 Reviewed-by: SoXX <fenpaws@noreply.localhost> Co-authored-by: Lennard Brinkhaus <lennard.brinkhaus@noreply.localhost> Co-committed-by: Lennard Brinkhaus <lennard.brinkhaus@noreply.localhost>
45 lines
1.1 KiB
Go
45 lines
1.1 KiB
Go
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
|
|
}
|