Context cancel() not cancelling


(Alex Leonhardt) #1

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


(Alex Leonhardt) #2

Okay, turns out i’m just not patient enough and the explanation why it doesn’t work (yet) comes later :wink: .


(system) closed #3

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.