Created
October 5, 2015 19:30
-
-
Save caelifer/c4c7cb8c58e33952c69f 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 | |
// Exersice #1 from http://whipperstacker.com/2015/10/05/3-trivial-concurrency-exercises-for-the-confused-newbie-gopher/ | |
import ( | |
"fmt" | |
"math/rand" | |
"sync" | |
"time" | |
) | |
/* | |
type Person interface { | |
GetReady(*sync.WaitGroup) | |
PutOnShoes(*sync.WaitGroup) | |
} | |
*/ | |
type person string | |
func (p person) GetReady(wg *sync.WaitGroup) { | |
fmt.Println(string(p), "started to get ready.") | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
t := time.Duration(rand.Intn(5)) * time.Second | |
time.Sleep(t) | |
fmt.Println(string(p), "spent", t, "getting ready.") | |
}() | |
} | |
func (p person) PutOnShoes(wg *sync.WaitGroup) { | |
fmt.Println(string(p), "started putting on shoes.") | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
t := time.Duration(rand.Intn(5)) * time.Second | |
time.Sleep(t) | |
fmt.Println(string(p), "spent", t, "putting on shoes.") | |
}() | |
} | |
type Alarm interface { | |
ArmTheAlarm() <-chan struct{} | |
} | |
type alarm struct{} | |
func (alarm) ArmTheAlarm() <-chan struct{} { | |
fmt.Println("Arming the alarm.") | |
done := make(chan struct{}) | |
go func() { | |
fmt.Println("Alarm is counting down.") | |
time.Sleep(5 * time.Second) | |
fmt.Println("Alarm is armed!") | |
done <- struct{}{} | |
}() | |
return done | |
} | |
func main() { | |
rand.Seed(0) | |
wg := new(sync.WaitGroup) | |
alice, bob := person("Alice"), person("Bob") | |
fmt.Println("Let's go for a walk!") | |
// Get ready | |
bob.GetReady(wg) | |
alice.GetReady(wg) | |
wg.Wait() | |
// Set the alarm | |
done := new(alarm).ArmTheAlarm() | |
// Put on shoes | |
alice.PutOnShoes(wg) | |
bob.PutOnShoes(wg) | |
wg.Wait() | |
fmt.Println("Exiting and locking the door.") | |
// Wait for the alarm to arm itself | |
<-done | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Live code - http://play.golang.org/p/m5anAc6P9d