Created
March 28, 2014 03:28
-
-
Save aodin/9824698 to your computer and use it in GitHub Desktop.
This file contains 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 ( | |
"log" | |
"sync" | |
"time" | |
) | |
// Global wait group | |
var jobs sync.WaitGroup | |
type Robot struct { | |
Name string | |
C chan bool | |
} | |
func New(name string) *Robot { | |
r := &Robot{Name: name, C: make(chan bool, 1)} | |
// Start the listen go routine | |
jobs.Add(1) | |
go func() { | |
// Receive Forever | |
for msg := range r.C { | |
log.Println("name:", name, msg) | |
} | |
jobs.Done() | |
}() | |
return r | |
} | |
func NewBroken(name string) *Robot { | |
r := &Robot{Name: name, C: make(chan bool, 1)} | |
jobs.Add(1) | |
go func() { | |
// Only receive once, then stop listening | |
msg := <- r.C | |
log.Println("name:", name, msg) | |
jobs.Done() | |
}() | |
return r | |
} | |
type Command struct { | |
robots []*Robot | |
} | |
func (c *Command) Send() { | |
for _, robot := range c.robots { | |
// Try sending | |
select { | |
case robot.C <- true: | |
continue | |
default: | |
continue | |
} | |
} | |
} | |
func (c *Command) SendEvery(d time.Duration) { | |
for now := range time.Tick(d) { | |
log.Println(now) | |
for _, robot := range c.robots { | |
select { | |
case robot.C <- true: | |
continue | |
default: | |
continue | |
} | |
} | |
} | |
} | |
func Control(robots ...*Robot) *Command { | |
return &Command{robots: robots} | |
} | |
func main() { | |
a := New("a") | |
b := NewBroken("b") | |
c := Control(a, b) | |
log.Println(c.robots) | |
c.SendEvery(time.Second) | |
// Wait for everything to finish | |
// jobs.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment