go: Misleading context.WithTimeout(): Timeout shouldn't start counting once you create the context

What version of Go are you using (go version)?

go1.13.5 darwin/amd64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

GO111MODULE=“” GOARCH=“amd64” GOBIN=“” GOCACHE=“/Users/david.cruz/Library/Caches/go-build” GOENV=“/Users/david.cruz/Library/Application Support/go/env” GOEXE=“” GOFLAGS=“” GOHOSTARCH=“amd64” GOHOSTOS=“darwin” GONOPROXY=“dummy” GONOSUMDB=“dummy” GOOS=“darwin” GOPATH=“/Users/david.cruz/Go” GOPRIVATE=“dummy” GOPROXY=“https://proxy.golang.org,direct” GOROOT=“/usr/local/go” GOSUMDB=“sum.golang.org” GOTMPDIR=“” GOTOOLDIR=“/usr/local/go/pkg/tool/darwin_amd64” GCCGO=“gccgo” AR=“ar” CC=“clang” CXX=“clang++” CGO_ENABLED=“1” GOMOD=“/Users/david.cruz/Go/src/dummy/go.mod” CGO_CFLAGS=“-g -O2” CGO_CPPFLAGS=“” CGO_CXXFLAGS=“-g -O2” CGO_FFLAGS=“-g -O2” CGO_LDFLAGS=“-g -O2” PKG_CONFIG=“pkg-config” GOGCCFLAGS=“-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/c4/ny3xl46x44q_s74l7p_3555jhkqrgp/T/go-build207377976=/tmp/go-build -gno-record-gcc-switches -fno-common”

What did you do?

ctx, cancel := context.WithTimeout(context.Background(), time.Duration(2)*time.Second) defer cancel() time.Sleep(3 * time.Second) err := foo(ctx)

What did you expect to see?

There shouldn’t be a “context deadline exceeded” error.

What did you see instead?

Function “foo” returned a “context deadline exceeded”

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 2
  • Comments: 15 (8 by maintainers)

Most upvoted comments

It may have been a bad decision but we can’t change it now. https://golang.org/doc/go1compat.

(In practice I see people use context.WithTimeout all the time.)