Skip to content

Instantly share code, notes, and snippets.

@psankar
Created June 14, 2017 05:01
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 psankar/4e5b2e563038ce3e9c17eb208c76168a to your computer and use it in GitHub Desktop.
Save psankar/4e5b2e563038ce3e9c17eb208c76168a to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"runtime"
"time"
)
type LED struct {
state bool
ticker *time.Ticker
}
func toggle(led *LED) {
led.state = !led.state
}
func looper(led *LED) {
for range led.ticker.C {
toggle(led)
}
}
func looper2(led *LED, q chan bool) {
for {
select {
case <-led.ticker.C:
toggle(led)
case <-q:
fmt.Println("Exiting the goroutine")
return
}
}
}
func main() {
fmt.Println("Initial number of GoRoutines: ", runtime.NumGoroutine())
led := &LED{state: true, ticker: time.NewTicker(time.Millisecond * 500)}
q := make(chan bool)
go looper2(led, q)
// go looper(led)
fmt.Println("Number of GoRoutines after a call to looper: ", runtime.NumGoroutine())
time.Sleep(2 * time.Second)
led.ticker.Stop()
fmt.Println("Number of GoRoutines after stopping the ticker: ", runtime.NumGoroutine())
q <- true
fmt.Println("Number of GoRoutines after sending a message on the quit channel: ", runtime.NumGoroutine())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment