Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Very simple supervisor in Go
package gosuper
type addFunc struct {
f func()
id chan uint64
}
type Supervisor struct {
exit chan uint64
addRoutine chan addFunc
routines map[uint64]func()
incId uint64
}
func NewSupervisor() *Supervisor {
super := &Supervisor{
exit: make(chan uint64),
addRoutine: make(chan addFunc),
routines: make(map[uint64]func()),
incId: 0,
}
// Listen for goroutine exits and restart
go func() {
for ; ; {
id := <-super.exit
if routine := super.routines[id]; routine != nil {
go super.start(id, routine)
}
}
}()
// Add a routine for watching
go func() {
addFunction := <-super.addRoutine
id := super.incId
super.incId = super.incId + 1
super.routines[id] = addFunction.f
addFunction.id <- id
}()
return super
}
// Run function and inform supervisor incase of panic
func (super *Supervisor) start(id uint64, routine func()) {
defer func() {
if err := recover(); err != nil {
super.exit <- id
}
}()
routine()
}
// Start a go routine and restart it if it panics
func (super *Supervisor) GoWatch(routine func()) {
idChan := make(chan uint64)
super.addRoutine <- addFunc{routine, idChan}
id := <-idChan
go super.start(id, routine)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.