> 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"
Will this be OK?
func ListenAndServe(ctx context.Context, srv *http.Server) error {
ctx,cancel := context.WitchCancel(ctx)
wg := sync.WaitGroup{}
defer wg.Wait()
wg.Add(1)
go func(ctx context.Context) {
defer cancel()
err := srv.ListenAndServe()
fmt.Println("Server err is", err)
On Thu, 6 Apr 2017 02:04:29 -0700 (PDT)
Kemal Hadimli wrote:
> Isn't the select processing order random? IIRC the only guarantee is
> "default" case is handled as a low priority.
>
> So, something like this maybe?
>
> select {
> case errCh <- err:
> default:
> select {
> case <-ctx.Done():
> }
Yes you're right, the processing order is pseudo random.
But my code also handle another edge case:
If `srv.ListenAndServe()` returns an error BEFORE we reach the code `case
err := <-errCh:`,
with `default` the error is ignored.
My code ensure that:
- there is no leaking goroutine
- returned err
Isn't the select processing order random? IIRC the only guarantee is
"default" case is handled as a low priority.
So, something like this maybe?
select {
case errCh <- err:
default:
select {
case <-ctx.Done():
}
}
Again, take this with a grain of salt. I didn't check the spec or code,
just off
I did it for a good reason:
If the context is canceled `srv.Shutdown` is called.
Then, `<-errCh` is not called anymore.
This code ensures that there is not leaking goroutine.
Le mercredi 5 avril 2017 07:13:19 UTC+2, Johnny Luo a écrit :
>
> func listenAndServe(ctx context.Context, srv *http.Server
func listenAndServe(ctx context.Context, srv *http.Server, errCh chan<-
error) {
err := srv.ListenAndServe()
select {
case errCh <- err:
case <-ctx.Done():
}
}
ListenAndServe is blocking function, so the select will not happen until
ListenAndServe return. and errCh become no use
On Wednes