Created
June 6, 2013 09:56
-
-
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 …
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
/* | |
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