What false From stop() in Go's context.AfterFunc Actually Means—and How to Wait for Cleanup Without RacesBrief · digest for November 27
Brief≈ 2 min

What false From stop() in Go's context.AfterFunc Actually Means—and How to Wait for Cleanup Without Races

You attach a cleanup callback using context.AfterFunc (added in Go 1.21) to close a connection on cancellation. Your work finishes early, you call stop(), and it returns false. It's tempting to assume cleanup has already finished, yet that isn't true.

false means one of two things: either the context canceled and your handler is running in a separate goroutine, or stop() was already called before. Crucially, stop() does not wait for cleanup to complete. Touch shared state immediately and you trigger a data race (two goroutines accessing the same data concurrently). Wait on a done channel unconditionally and stop() == true will deadlock forever because the handler never runs.

done := make(chan struct{})
stop := context.AfterFunc(ctx, func() {
    // Close the channel even if cleanup panics
    defer close(done)
    cleanup()
})

// Call stop() exactly once:
// true  -> cleanup won't run, do not wait on done;
// false -> cleanup already started, wait for it to finish.
if !stop() {
    <-done
}

This pattern covers both paths safely, even if the context was already canceled before AfterFunc ran. Just never call stop() a second time inside if !stop() { <-done }: the second call always returns false, leaving your code stuck on the channel forever if the first call returned true.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 2