dendrite/roomserver/internal/input/input_fifo.go

65 lines
1.3 KiB
Go
Raw Normal View History

package input
import (
"sync"
)
type fifoQueue struct {
2021-06-28 07:31:21 -05:00
tasks []*inputTask
count int
mutex sync.Mutex
notifs chan struct{}
}
func newFIFOQueue() *fifoQueue {
q := &fifoQueue{
2021-06-28 05:18:11 -05:00
notifs: make(chan struct{}, 1),
}
return q
}
2021-06-28 07:31:21 -05:00
func (q *fifoQueue) push(frame *inputTask) {
q.mutex.Lock()
defer q.mutex.Unlock()
2021-06-28 07:31:21 -05:00
q.tasks = append(q.tasks, frame)
q.count++
select {
case q.notifs <- struct{}{}:
default:
}
}
2021-06-28 07:34:54 -05:00
// pop returns the first item of the queue, if there is one.
// The second return value will indicate if a task was returned.
// You must check this value, even after calling wait().
func (q *fifoQueue) pop() (*inputTask, bool) {
q.mutex.Lock()
defer q.mutex.Unlock()
if q.count == 0 {
return nil, false
}
2021-06-28 07:31:21 -05:00
frame := q.tasks[0]
q.tasks[0] = nil
q.tasks = q.tasks[1:]
q.count--
if q.count == 0 {
// Force a GC of the underlying array, since it might have
// grown significantly if the queue was hammered for some reason
2021-06-28 07:31:21 -05:00
q.tasks = nil
}
return frame, true
}
2021-06-28 07:34:54 -05:00
// wait returns a channel which can be used to detect when an
// item is waiting in the queue.
func (q *fifoQueue) wait() <-chan struct{} {
q.mutex.Lock()
defer q.mutex.Unlock()
2021-06-28 07:31:21 -05:00
if q.count > 0 && len(q.notifs) == 0 {
ch := make(chan struct{})
close(ch)
return ch
}
return q.notifs
}