Skip to content

Instantly share code, notes, and snippets.

@sermojohn
Last active May 13, 2018 22:51
Show Gist options
  • Save sermojohn/527d47d236362fa6cf6182fd2947520a to your computer and use it in GitHub Desktop.
Save sermojohn/527d47d236362fa6cf6182fd2947520a to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"runtime"
"time"
)
// GetWebResults test
func GetWebResults(cancel chan bool) {
// START OMIT
c := make(chan string)
go func() {
for {
select {
case <-cancel:
c <- "cancelled"
return
}
}
}()
timeout := time.After(100 * time.Millisecond)
for {
select { // HL
case <-c: // HL
fmt.Println("returned")
return
case <-timeout: // HL
fmt.Println("timed-out")
// comment-in either return or cancel channel signal
// return
cancel <- true
}
}
}
func main() {
cancel := make(chan bool) // just to simulate case we want to cancel
GetWebResults(cancel)
if activeGoroutines := runtime.NumGoroutine(); activeGoroutines != 1 {
fmt.Printf("program should stop gracefully. num of active go-routines:%v", activeGoroutines)
}
}
@sermojohn
Copy link
Author

Manual cancellation of go-routine using channel.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment