Last active
September 2, 2018 06:58
-
-
Save dulao5/1542c54fb6a8c8fdcdff674a0372f711 to your computer and use it in GitHub Desktop.
golang concurrency exercise
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
// https://talks.golang.org/2012/concurrency.slide#36 | |
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
type Message struct { | |
str string | |
wait chan bool | |
} | |
func boring(msg string) <-chan Message { | |
c := make(chan Message) | |
waitForIt := make(chan bool) // Shared between all messages. | |
go func() { | |
for i := 0; ; i++ { | |
c <- Message{ | |
str: fmt.Sprintf("%s: %d", msg, i), | |
wait: waitForIt, | |
} | |
time.Sleep(time.Duration(rand.Intn(2e3)) * time.Millisecond) | |
<-waitForIt | |
} | |
}() | |
return c | |
} | |
func fanIn(input1, input2 <-chan Message) <-chan Message { | |
c := make(chan Message) | |
go func() { | |
for { | |
select { | |
case i1 := <-input1: | |
c <- i1 | |
case i2 := <-input2: | |
c <- i2 | |
} | |
} | |
}() | |
return c | |
} | |
func main() { | |
timesLimit := 5 | |
c := fanIn(boring("Joe"), boring("Ann")) | |
for i := 0; i < timesLimit; i++ { | |
timeout := time.After(5 * time.Second) | |
group := make([]Message, 0) | |
for len(group) < 2 { | |
select { | |
case msg := <-c: | |
fmt.Println(msg.str) | |
group = append(group, msg) | |
case <-timeout: | |
fmt.Printf("No. %d: You talk too much.\n", i) | |
return | |
} | |
} | |
for _, msg := range group { | |
msg.wait <- true | |
} | |
} | |
fmt.Println("You're boring; I'm leaving.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment