Last active
September 21, 2015 09:46
-
-
Save calmh/1b1c0d37a167d7e9fa2d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
"github.com/thejerf/suture" | |
) | |
func main() { | |
// We have a main supervisor at the top of the tree. | |
mainSup := suture.NewSimple("main") | |
mainSup.ServeBackground() | |
// It has a child supervisor that also has some services on it at creation | |
// time. | |
s := newSomeService() | |
mainSup.Add(s) | |
// We can add more stuff at run time without issues. | |
mainSup.Add(newChildService("three")) | |
// However we cannot add stuff to the child supervisor, or we get a data | |
// race. | |
s.AddChild("four") | |
time.Sleep(5 * time.Second) | |
} | |
// someService does more than one thing, so it embeds a Supervisor and adds | |
// some services at creation time. | |
type someService struct { | |
*suture.Supervisor | |
// other stuff | |
} | |
func newSomeService() *someService { | |
s := &someService{ | |
Supervisor: suture.NewSimple("someService"), | |
} | |
s.Add(newChildService("one")) | |
s.Add(newChildService("two")) | |
return s | |
} | |
func (s *someService) AddChild(name string) { | |
s.Add(newChildService(name)) | |
} | |
// childService is just something that does stuff. | |
type childService struct { | |
name string | |
stop chan struct{} | |
} | |
func newChildService(name string) *childService { | |
return &childService{ | |
name: name, | |
stop: make(chan struct{}), | |
} | |
} | |
func (c *childService) Serve() { | |
ticker := time.NewTicker(time.Second) | |
for { | |
select { | |
case <-c.stop: | |
return | |
case <-ticker.C: | |
fmt.Println("tick on", c.name) | |
} | |
} | |
} | |
func (c *childService) Stop() { | |
close(c.stop) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment