> Is it OK to use context cancellation for stopping long running functions ?
yes, i d say so. About contexts, https://www.youtube.com/watch?v=LSzR0VEraWw https://www.youtube.com/watch?v=8M90t0KvEDY >From scratch, with some mocks to test&try. package main import ( "context" "log" "time" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), 2*time. Millisecond) defer cancel() var err error listenSig := make(chan error) go func() { listenSig <- <-listenAndServe() }()//IRL, not sure if that will return if server has shutdown. // this is unclear at https://beta.golang.org/src/net/http/server.go?s=79791:79837#L2615 // i d say its all about timeouts. select { case err = <-listenSig: log.Println("server soft end") case <-ctx.Done(): log.Println("context ended") log.Println("server hard stop") if err = shutdown( /*context.Background()*/ ); err == nil { err = ctx.Err() } log.Println("server ended") } log.Println(err) } func listenAndServe() chan error { e := make(chan error) go func() { <-time.After(time.Second) e <- nil }() return e } func shutdown() error { <-time.After(2 * time.Second) return nil } that being said, server.Shutdown seems blocking, https://beta.golang.org/pkg/net/http/#Server.Shutdown > Shutdown ... waiting indefinitely for connections to return to idle and then shut down. https://beta.golang.org/src/net/http/server.go?s=74304:74358#L2440 If so, d go func that one and put its err to a sink logger. It will hang there until all clients are out, so the server must be configured with timeouts. Or use a context with deadline ? I m not sure what s the best, maybe both are needed ? It looks likes this ctx parameter is sugar only. Apart, does server.Shutdown allows a straight restart ? +/- like if i d use socket_reuse port/addr? > This code ensures that there is not leaking goroutine. How do you know ? I mean for race detection there is a tool, for routine leak see those findings, https://github.com/fortytw2/leaktest https://godoc.org/github.com/anacrolix/missinggo#GoroutineLeakCheck https://github.com/google/gops https://medium.com/golangspec/goroutine-leak-400063aef468 https://github.com/golang/go/issues/12989 https://github.com/golang/go/issues/5308 https://github.com/golang/go/issues/6705 It has been set to "Adding Release=None to all Priority=Someday bugs." On Tuesday, April 4, 2017 at 8:02:16 PM UTC+2, Pierre Durand wrote: > > Hello > > I wrote a small helper to stop an HTTP Server when a Context is canceled. > https://play.golang.org/p/Gl8APynVdh > > What do you think ? > Is it OK to use context cancellation for stopping long running functions ? > -- 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.