Skip to content

time: AfterFunc documentation unclear about misuse of Timer.C  #60811

@ruzv

Description

@ruzv

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

$ go version
go version go1.20.4 darwin/amd64

Does this issue reproduce with the latest release?

Yes

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

go env Output
$ go env
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/rudolfszvejs/Library/Caches/go-build"
GOENV="/Users/rudolfszvejs/Library/Application Support/go/env"
GOEXE=""
GOEXPERIMENT=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOINSECURE=""
GOMODCACHE="/Users/rudolfszvejs/go/pkg/mod"
GONOPROXY="code.tdlbox.com"
GONOSUMDB="code.tdlbox.com"
GOOS="darwin"
GOPATH="/Users/rudolfszvejs/go"
GOPRIVATE="code.tdlbox.com"
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/Cellar/go/1.20.4/libexec"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/Cellar/go/1.20.4/libexec/pkg/tool/darwin_amd64"
GOVCS=""
GOVERSION="go1.20.4"
GCCGO="gccgo"
GOAMD64="v1"
AR="ar"
CC="cc"
CXX="c++"
CGO_ENABLED="1"
GOMOD="/Users/rudolfszvejs/go/src/code.tdlbox.com/loadero/rnd/sales-scrapper/go.mod"
GOWORK=""
CGO_CFLAGS="-O2 -g"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-O2 -g"
CGO_FFLAGS="-O2 -g"
CGO_LDFLAGS="-O2 -g"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -arch x86_64 -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-l
ength=0 -fdebug-prefix-map=/var/folders/65/207sntgd6rjcr3bxl5zctw9m0000gn/T/go-build3662304365=/tm
p/go-build -gno-record-gcc-switches -fno-common"

What did you do?

timer := time.AfterFunc(time.Second, func() { time.Sleep(5 * time.Second) })

time.Sleep(2 * time.Second)

if !timer.Stop() {
    <-timer.C
}

Creating a new Timer via AfterFunc does not initialize the Timer.C field, making the code above deadlock. Link to go.dev/play

What did you expect to see?

Documentation clearly specifying that Timer.C shouldn't be used when Timer is created using AfterFunc.

What did you see instead?

In the documentation, there are multiple examples of

if !timer.Stop() {
    <-timer.C
}

making me think that Timer.C is always available.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DocumentationIssues describing a change to documentation.FrozenDueToAgeNeedsFixThe path to resolution is known, but the work has not been done.help wanted

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions