better tasking

This commit is contained in:
Jesse Duffield 2019-06-15 15:41:44 +10:00
parent 383f8a51e3
commit e3da07d0b2

View file

@ -8,16 +8,20 @@ import (
) )
type TaskManager struct { type TaskManager struct {
waitingTasks []*Task waitingTask *Task
currentTask *Task currentTask *Task
waitingMutex sync.Mutex waitingMutex sync.Mutex
Log *logrus.Entry taskIDMutex sync.Mutex
Log *logrus.Entry
waitingTaskAlerts chan struct{}
newTaskId int
} }
type Task struct { type Task struct {
stop chan struct{} stop chan struct{}
notifyStopped chan struct{} notifyStopped chan struct{}
Log *logrus.Entry Log *logrus.Entry
f func(chan struct{})
} }
func NewTaskManager(log *logrus.Entry) *TaskManager { func NewTaskManager(log *logrus.Entry) *TaskManager {
@ -25,24 +29,30 @@ func NewTaskManager(log *logrus.Entry) *TaskManager {
} }
func (t *TaskManager) NewTask(f func(stop chan struct{})) error { func (t *TaskManager) NewTask(f func(stop chan struct{})) error {
// TODO: topple the previous task if there is a new one
go func() { go func() {
t.taskIDMutex.Lock()
t.newTaskId++
taskID := t.newTaskId
t.taskIDMutex.Unlock()
t.waitingMutex.Lock() t.waitingMutex.Lock()
defer t.waitingMutex.Unlock() defer t.waitingMutex.Unlock()
if taskID < t.newTaskId {
if t.currentTask != nil { return
t.currentTask.Stop()
} }
stop := make(chan struct{}, 1) // we don't want to block on this in case the task already returned stop := make(chan struct{}, 1) // we don't want to block on this in case the task already returned
notifyStopped := make(chan struct{}) notifyStopped := make(chan struct{})
if t.currentTask != nil {
t.currentTask.Stop()
}
t.currentTask = &Task{ t.currentTask = &Task{
stop: stop, stop: stop,
notifyStopped: notifyStopped, notifyStopped: notifyStopped,
Log: t.Log, Log: t.Log,
f: f,
} }
go func() { go func() {