> > While this is running, your select won't be receiving on the quit > channel, even if it is non-nil. > If you want to be able to cancel it, you'll need to make the code in > the loop responsive to the quit channel > (for example, by using a select like you're using in f already).
The default select case does it: https://play.golang.org/p/jlfaXu6TZ8L Here's another way: https://play.golang.org/p/gEDef3LolAZ Matt On Friday, March 16, 2018 at 9:45:00 AM UTC-5, Sathish VJ wrote: > > All the examples I've seen use some kind of ticker to run various cases of > a select statement. But how does one run a long running task that is still > cancelable? > > > In the example below the quit part is never reached. > > https://play.golang.org/p/PLGwrUvKaqn (it does not run properly on > play.golang.org). > > package main > > > import ( > "fmt" > "os" > "time" > ) > > > func f(quit chan bool) { > for { > select { > case <-time.After(0 * time.Second): > // start long running task immediately. > for { > time.Sleep(500 * time.Millisecond) > fmt.Printf(". ") > } > case <-quit: > fmt.Println("quit called") > //deallocate resources in other long running task and then return > from function. > os.Exit(0) // or return > } > } > } > > > func main() { > var quit chan bool > go f(quit) > > > println("quit sending ... ") > quit <- true > println("after quit sent") > > > var i chan int > <-i > } > > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.