Skip to content

Instantly share code, notes, and snippets.

@bjdean
Created June 6, 2013 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjdean/5720497 to your computer and use it in GitHub Desktop.
Save bjdean/5720497 to your computer and use it in GitHub Desktop.
What happens to the goroutines? On exit (once main goes away, or if os.Exit is called) the goroutines are killed off (no deferred functions are run). Note - to get goroutines to quit a 'broadcast' quit channel can be created - as a closed channel starts to return which means a global quit channel can be included in all selects in goroutines and …
/*
What happens to the goroutines?
On exit (once main goes away, or if os.Exit is called) the goroutines
are killed off (no deferred functions are run).
Note - to get goroutines to quit a 'broadcast' quit channel can be
created - as a closed channel starts to return which means a global quit
channel can be included in all selects in goroutines and they'll only
fire when the quit channel is closed (see builting close documentation)
*/
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
defer main_bye()
rand.Seed(time.Now().Unix())
for _, name := range []string{"Bob", "Fred", "Anne"} {
go sleepy(name)
}
sleepTime := time.Duration(rand.Intn(20)) * time.Second
fmt.Println("The end of the world is", sleepTime, "away")
go countDown(sleepTime)
time.Sleep(sleepTime)
}
func main_bye() {
fmt.Println("The End Has Come")
}
func countDown ( timeLeft time.Duration ) {
for {
fmt.Println("Tick!", timeLeft, "left...")
timeLeft -= time.Second
time.Sleep(time.Second)
}
}
func sleepy(name string) {
defer sleepy_bye(name)
for {
sleepTime := time.Duration(rand.Intn(5)) * time.Second
fmt.Println("Sleepy", name, "sleeping for", sleepTime)
time.Sleep(sleepTime)
}
}
func sleepy_bye(name string) {
fmt.Println("Bye from Sleepy", name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment