Created
August 14, 2018 15:15
-
-
Save jhunt/fca00e511a1680667c173f7338ff4e0d 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 "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