Files
livekit/pkg/utils/opsqueue.go
Raja Subramanian 2959eebca8 Introducing OpsQueue (#463)
* Introducing OpsQueue

Creating a PR to get feedback on standardizing on this concept.

Can be used for callbacks.
Already a couple of places use this construct. Wondering if we
should standardize on this across the board.
Just changing one place to use the new struct. Another place
that I know of which uses this pattern is the telemetry package.

* atomic flag -> bool
2022-02-25 11:56:26 +05:30

55 lines
657 B
Go

package utils
import (
"sync"
)
const (
MaxOps = 50
)
type OpsQueue struct {
lock sync.RWMutex
ops chan func()
isStopped bool
}
func NewOpsQueue() *OpsQueue {
return &OpsQueue{
ops: make(chan func(), MaxOps),
}
}
func (oq *OpsQueue) Start() {
go oq.process()
}
func (oq *OpsQueue) Stop() {
oq.lock.Lock()
if oq.isStopped {
oq.lock.Unlock()
return
}
oq.isStopped = true
close(oq.ops)
oq.lock.Unlock()
}
func (oq *OpsQueue) Enqueue(op func()) {
oq.lock.RLock()
if oq.isStopped {
oq.lock.RUnlock()
return
}
oq.ops <- op
oq.lock.RUnlock()
}
func (oq *OpsQueue) process() {
for op := range oq.ops {
op()
}
}