I'm new in Golang and I have some confused about WithCancel and WithTimeout when I learn golang's context part.
Show the code.
package main
import (
"context"
"fmt"
"time"
)
func someHandler() {
//ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
go doSth(ctx)
time.Sleep(3 * time.Second)
cancel()
}
func doSth(ctx context.Context) {
var i = 1
for {
time.Sleep(1 * time.Second)
select {
case <-ctx.Done():
fmt.Println("done")
return
default:
fmt.Printf("work %d seconds: \n", i)
}
i++
}
}
func main() {
fmt.Println("start...")
someHandler()
fmt.Println("end.")
}
Result:
// when use WithCancel
//
start...
work 1 seconds:
work 2 seconds:
end.
// when use WithTimeout
start...
work 1 seconds:
done
end.
My question is: why doesn't it print 'done' when I use withCancel but withTimeout does print it?