I’ve followed Francesc’s (justforfunc) example on a simple use of context with cancellation, but it won’t actually cancel the execution ?
here’s the code:
package main
import (
"context"
"fmt"
"time"
)
func sleepAndTalk(ctx context.Context, t time.Duration, txt string) {
time.Sleep(t)
fmt.Println(txt)
}
func main() {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
go func() {
time.Sleep(time.Second)
cancel()
}()
sleepAndTalk(ctx, 5*time.Second, "yolo")
}
In theory, the execution should be cancelled after a second, however, it isn’t and continues to wait for 5 seconds to then output the text yolo.
It also doesn’t seem to work on go playground, does anyone know why this doesn’t work?
https://play.golang.org/p/edsDZkYylrF
Thanks!
Alex