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

leadership: avoid potential data race (#6636) #6639

Closed
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
10 changes: 8 additions & 2 deletions pkg/election/leadership.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package election

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

"github.com/pingcap/failpoint"
Expand Down Expand Up @@ -54,8 +55,9 @@ type Leadership struct {
leaderKey string
leaderValue string

keepAliveCtx context.Context
keepAliveCancelFunc context.CancelFunc
keepAliveCtx context.Context
keepAliveCancelFunc context.CancelFunc
keepAliveCancelFuncLock sync.Mutex
}

// NewLeadership creates a new Leadership.
Expand Down Expand Up @@ -137,7 +139,9 @@ func (ls *Leadership) Keep(ctx context.Context) {
if ls == nil {
return
}
ls.keepAliveCancelFuncLock.Lock()
ls.keepAliveCtx, ls.keepAliveCancelFunc = context.WithCancel(ctx)
ls.keepAliveCancelFuncLock.Unlock()
go ls.getLease().KeepAlive(ls.keepAliveCtx)
}

Expand Down Expand Up @@ -230,8 +234,10 @@ func (ls *Leadership) Reset() {
if ls == nil || ls.getLease() == nil {
return
}
ls.keepAliveCancelFuncLock.Lock()
if ls.keepAliveCancelFunc != nil {
ls.keepAliveCancelFunc()
}
ls.keepAliveCancelFuncLock.Unlock()
ls.getLease().Close()
}