]> Cypherpunks.ru repositories - gostls13.git/commitdiff
context: add lock in Cause to avoid race
authorIan Lance Taylor <iant@golang.org>
Mon, 28 Nov 2022 18:33:04 +0000 (10:33 -0800)
committerGopher Robot <gobot@golang.org>
Mon, 28 Nov 2022 19:33:02 +0000 (19:33 +0000)
Change-Id: I8d970e8db859bdd17390cfbc22cc2ba0d326ed0c
Reviewed-on: https://go-review.googlesource.com/c/go/+/453735
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
Run-TryBot: Ian Lance Taylor <iant@google.com>
Reviewed-by: Sameer Ajmani <sameer@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>

src/context/context.go
src/context/context_test.go
src/context/x_test.go

index f39abe91e2cd06407b4443bf05434c95917f57dd..f3fe1a474e1fa10ab11f4a180a539d3d66e26dcd 100644 (file)
@@ -285,6 +285,8 @@ func withCancel(parent Context) *cancelCtx {
 // Cause returns nil if c has not been canceled yet.
 func Cause(c Context) error {
        if cc, ok := c.Value(&cancelCtxKey).(*cancelCtx); ok {
+               cc.mu.Lock()
+               defer cc.mu.Unlock()
                return cc.cause
        }
        return nil
index 593a7b152187a093a1e81978b71bd674d0334592..eb5a86b3c608790d3b26733b26879fbbb02484f6 100644 (file)
@@ -5,6 +5,7 @@
 package context
 
 import (
+       "errors"
        "fmt"
        "math/rand"
        "runtime"
@@ -934,3 +935,22 @@ func XTestCause(t testingT) {
                }
        }
 }
+
+func XTestCauseRace(t testingT) {
+       cause := errors.New("TestCauseRace")
+       ctx, cancel := WithCancelCause(Background())
+       go func() {
+               cancel(cause)
+       }()
+       for {
+               // Poll Cause, rather than waiting for Done, to test that
+               // access to the underlying cause is synchronized properly.
+               if err := Cause(ctx); err != nil {
+                       if err != cause {
+                               t.Errorf("Cause returned %v, want %v", err, cause)
+                       }
+                       break
+               }
+               runtime.Gosched()
+       }
+}
index d3adb381d655231f436545d54caaeebfc4415dcb..a2d814f8ead768bac71376473e9b350fb0226587 100644 (file)
@@ -30,3 +30,4 @@ func TestInvalidDerivedFail(t *testing.T)              { XTestInvalidDerivedFail
 func TestDeadlineExceededSupportsTimeout(t *testing.T) { XTestDeadlineExceededSupportsTimeout(t) }
 func TestCustomContextGoroutines(t *testing.T)         { XTestCustomContextGoroutines(t) }
 func TestCause(t *testing.T)                           { XTestCause(t) }
+func TestCauseRace(t *testing.T)                       { XTestCauseRace(t) }