Last active
May 13, 2018 22:51
-
-
Save sermojohn/527d47d236362fa6cf6182fd2947520a to your computer and use it in GitHub Desktop.
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
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Manual cancellation of go-routine using channel.