Skip to content

Instantly share code, notes, and snippets.

@jhunt
Created August 14, 2018 15:15
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 jhunt/fca00e511a1680667c173f7338ff4e0d to your computer and use it in GitHub Desktop.
Save jhunt/fca00e511a1680667c173f7338ff4e0d to your computer and use it in GitHub Desktop.
package main
import "fmt"
func main() {
chans := make([]chan int, 4)
for i := range chans {
chans[i] = make(chan int, 0)
}
go client(1, chans[0], 2)
go client(2, chans[1], 3)
go client(3, chans[2], 5)
go client(4, chans[3], 1)
n := 100
for {
for i := range chans {
sendit(chans, i, n)
}
n++
}
}
func sendit(chans []chan int, i int, n int) {
defer func() {
if r := recover(); r != nil {
fmt.Printf("PARENT: chans[%d] closed; nullifying.\n", i)
chans[i] = nil
}
}()
if chans[i] != nil {
fmt.Printf("PARENT: sending message to chans[%d]\n", i)
chans[i] <- n
}
}
func client(id int, ch chan int, max int) {
for i := 0; i < max; i++ {
msg := <-ch
fmt.Printf("CHILD %d: received message %d/%d: (%d)\n", id, i+1, max, msg)
}
fmt.Printf("CHILD %d: shutting down.\n", id)
close(ch)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment