Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/context/benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,3 +208,42 @@ func BenchmarkErrCanceled(b *testing.B) {
}
}
}

func BenchmarkErrOKParallel(b *testing.B) {
ctx, cancel := WithCancel(Background())
defer cancel()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
if err := ctx.Err(); err != nil {
b.Fatalf("ctx.Err() = %v", err)
}
}
})
}

func BenchmarkErrCanceledParallel(b *testing.B) {
ctx, cancel := WithCancel(Background())
cancel()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
if err := ctx.Err(); err == nil {
b.Fatalf("ctx.Err() = %v", err)
}
}
})
}

// BenchmarkErrCanceledParallelDistinct gives each goroutine its own canceled
// context, so the contexts share nothing with each other. Any contention here
// is contention on state shared by every canceled context in the program.
func BenchmarkErrCanceledParallelDistinct(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
ctx, cancel := WithCancel(Background())
cancel()
for pb.Next() {
if err := ctx.Err(); err == nil {
b.Fatalf("ctx.Err() = %v", err)
}
}
})
}
6 changes: 5 additions & 1 deletion src/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,11 @@ func (c *cancelCtx) Err() error {
// An atomic load is ~5x faster than a mutex, which can matter in tight loops.
if err := c.err.Load(); err != nil {
// Ensure the done channel has been closed before returning a non-nil error.
<-c.Done()
// closedchan is closed at init and shared by every canceled context, so
// receiving from it would take one process-global lock for nothing.
if done := c.Done(); done != closedchan {
<-done
}
return err.(error)
}
return nil
Expand Down