Implementation of #1 exercise on http://whipperstacker.com/2015/10/05/3-trivial-concurrency-exercises-for-the-confused-newbie-gopher
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" | |
"math/rand" | |
"sync" | |
"time" | |
) | |
var wg sync.WaitGroup | |
func main() { | |
done := make(chan bool) | |
rand.Seed(time.Now().UTC().UnixNano()) | |
wg.Add(2) | |
go getReady("Alice") | |
go getReady("Bob") | |
wg.Wait() | |
wg.Add(1) | |
go armAlarm() | |
go putShoes("Alice", done) | |
go putShoes("Bob", done) | |
for i := 0; i < 2; i++ { | |
<-done | |
} | |
fmt.Println("Exiting and locking the door.") | |
wg.Wait() | |
} | |
func getReady(person string) { | |
wait := randomize(6, 9) | |
fmt.Println(fmt.Sprintf("%s started getting ready", person)) | |
time.Sleep(time.Duration(wait) * time.Second) | |
fmt.Println(fmt.Sprintf("%s spent %d seconds getting ready", person, wait)) | |
wg.Done() | |
} | |
func putShoes(person string, done chan bool) { | |
wait := randomize(3, 4) | |
fmt.Println(fmt.Sprintf("%s started putting shoes", person)) | |
time.Sleep(time.Duration(wait) * time.Second) | |
fmt.Println(fmt.Sprintf("%s spent %d seconds putting shoes", person, wait)) | |
done <- true | |
} | |
func armAlarm() { | |
fmt.Println("Arming alarm.") | |
time.Sleep(10 * time.Millisecond) | |
fmt.Println("Arming is counting down.") | |
time.Sleep(5 * time.Second) | |
fmt.Println("Alarm armed.") | |
wg.Done() | |
} | |
func randomize(min, max int) int { | |
return min + rand.Intn(max) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment