Skip to content

Instantly share code, notes, and snippets.

@aodin
Created March 28, 2014 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aodin/9824698 to your computer and use it in GitHub Desktop.
Save aodin/9824698 to your computer and use it in GitHub Desktop.
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