mirror of
https://github.com/livekit/livekit.git
synced 2026-07-18 09:36:28 +00:00
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
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user