github.com/leg100/ots@v0.0.7-0.20210919080622-034055ced4bd/agent/terminator.go (about) 1 package agent 2 3 import "sync" 4 5 type Cancelable interface { 6 Cancel(force bool) 7 } 8 9 // Terminator handles canceling items using their ID 10 type Terminator struct { 11 // mapping maps ID to cancelable item 12 mapping map[string]Cancelable 13 14 mu sync.Mutex 15 } 16 17 func NewTerminator() *Terminator { 18 return &Terminator{ 19 mapping: make(map[string]Cancelable), 20 } 21 } 22 23 func (t *Terminator) CheckIn(id string, job Cancelable) { 24 t.mu.Lock() 25 defer t.mu.Unlock() 26 27 t.mapping[id] = job 28 } 29 30 func (t *Terminator) CheckOut(id string) { 31 t.mu.Lock() 32 defer t.mu.Unlock() 33 34 delete(t.mapping, id) 35 } 36 37 func (t *Terminator) Cancel(id string, force bool) { 38 t.mu.Lock() 39 defer t.mu.Unlock() 40 41 if job, ok := t.mapping[id]; ok { 42 job.Cancel(force) 43 } 44 }