Skip to content

Instantly share code, notes, and snippets.

@aodin aodin/gist:9824698
Created Mar 28, 2014

Embed
What would you like to do?
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
You can’t perform that action at this time.