Skip to content

Instantly share code, notes, and snippets.

@arosh
Last active December 17, 2016 17:13
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 arosh/f51651418ec6f320366d1176de0e3335 to your computer and use it in GitHub Desktop.
Save arosh/f51651418ec6f320366d1176de0e3335 to your computer and use it in GitHub Desktop.
goroutine cancel
package main
import (
"fmt"
"time"
)
func main() {
cancel := make(chan struct{})
go func() {
time.Sleep(3 * time.Second)
fmt.Println("Cancel!")
cancel <- struct{}{}
// close(cancel) is also OK!
}()
wasCanceled := func() bool {
select {
case <-cancel:
return true
default:
return false
}
}
i := 1
for {
if wasCanceled() {
break
}
fmt.Printf("i = %v\n", i)
time.Sleep(100 * time.Millisecond)
i += 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment