Skip to content

Instantly share code, notes, and snippets.

@cengiz-io
Last active December 21, 2020 09:10
Show Gist options
  • Save cengiz-io/530b6dd2ee0b007cb941 to your computer and use it in GitHub Desktop.
Save cengiz-io/530b6dd2ee0b007cb941 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
var peopleGroup sync.WaitGroup
var alarmGroup sync.WaitGroup
func random(min, max int64) int64 {
rand.Seed(time.Now().UTC().UnixNano())
return rand.Int63n(max-min) + min
}
type Person struct {
name string
}
type Task struct {
desc string
minTime int64
maxTime int64
}
func PerformTask(who *Person, task *Task) {
defer peopleGroup.Done()
fmt.Printf("%s started %s\n", who.name, task.desc)
duration := random(task.minTime, task.maxTime)
time.Sleep(time.Duration(duration) * time.Second)
fmt.Printf("%s spent %d seconds %s\n", who.name, duration, task.desc)
}
func AlarmTick() {
defer alarmGroup.Done()
fmt.Println("Alarm is counting down")
time.Sleep(60 * time.Second)
fmt.Println("Alarm is armed")
}
func main() {
getReady := Task{minTime: 60, maxTime: 90, desc: "getting ready"}
wearShoes := Task{minTime: 35, maxTime: 45, desc: "putting on shoes"}
peopleGroup.Add(2)
alice := Person{name: "Alice"}
bob := Person{name: "Bob"}
fmt.Println("Let's go for a walk")
go PerformTask(&alice, &getReady)
go PerformTask(&bob, &getReady)
peopleGroup.Wait()
alarmGroup.Add(1)
fmt.Println("Arming alarm")
go AlarmTick()
peopleGroup.Add(2)
go PerformTask(&alice, &wearShoes)
go PerformTask(&bob, &wearShoes)
peopleGroup.Wait()
fmt.Println("Exiting and locking the door.")
alarmGroup.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment