Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sqlbase: avoid a race in sqlbase.CancelChecker #35548

Merged
merged 1 commit into from
Mar 8, 2019
Merged
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
14 changes: 10 additions & 4 deletions pkg/sql/sqlbase/cancel_checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@

package sqlbase

import "context"
import (
"context"
"sync/atomic"
)

// CancelChecker is a helper object for repeatedly checking whether the associated context
// has been canceled or not. Encapsulates all logic for waiting for cancelCheckInterval
Expand All @@ -25,7 +28,7 @@ type CancelChecker struct {
ctx context.Context

// Number of times Check() has been called since last context cancellation check.
callsSinceLastCheck int32
callsSinceLastCheck uint32
}

// NewCancelChecker returns a new CancelChecker.
Expand All @@ -42,7 +45,7 @@ func (c *CancelChecker) Check() error {
// bitwise AND instead of division.
const cancelCheckInterval = 1024

if c.callsSinceLastCheck%cancelCheckInterval == 0 {
if atomic.LoadUint32(&c.callsSinceLastCheck)%cancelCheckInterval == 0 {
select {
case <-c.ctx.Done():
// Once the context is canceled, we no longer increment
Expand All @@ -52,7 +55,10 @@ func (c *CancelChecker) Check() error {
default:
}
}
c.callsSinceLastCheck++

// Increment. This may rollover when the 32-bit capacity is reached,
// but that's all right.
atomic.AddUint32(&c.callsSinceLastCheck, 1)
return nil
}

Expand Down