Skip to content

Commit cfdcdff

Browse files
ti-chi-botlhy1024
andauthored
leadership: avoid potential data race (#6636) (#6702)
close #6635, ref #6636 Signed-off-by: lhy1024 <admin@liudos.us> Co-authored-by: lhy1024 <admin@liudos.us>
1 parent 898dde2 commit cfdcdff

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

server/election/leadership.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ package election
1616

1717
import (
1818
"context"
19+
"sync"
1920
"sync/atomic"
2021

2122
"github.com/pingcap/failpoint"
@@ -54,8 +55,9 @@ type Leadership struct {
5455
leaderKey string
5556
leaderValue string
5657

57-
keepAliveCtx context.Context
58-
keepAliveCancelFunc context.CancelFunc
58+
keepAliveCtx context.Context
59+
keepAliveCancelFunc context.CancelFunc
60+
keepAliveCancelFuncLock sync.Mutex
5961
}
6062

6163
// NewLeadership creates a new Leadership.
@@ -137,7 +139,9 @@ func (ls *Leadership) Keep(ctx context.Context) {
137139
if ls == nil {
138140
return
139141
}
142+
ls.keepAliveCancelFuncLock.Lock()
140143
ls.keepAliveCtx, ls.keepAliveCancelFunc = context.WithCancel(ctx)
144+
ls.keepAliveCancelFuncLock.Unlock()
141145
go ls.getLease().KeepAlive(ls.keepAliveCtx)
142146
}
143147

@@ -230,8 +234,10 @@ func (ls *Leadership) Reset() {
230234
if ls == nil || ls.getLease() == nil {
231235
return
232236
}
237+
ls.keepAliveCancelFuncLock.Lock()
233238
if ls.keepAliveCancelFunc != nil {
234239
ls.keepAliveCancelFunc()
235240
}
241+
ls.keepAliveCancelFuncLock.Unlock()
236242
ls.getLease().Close()
237243
}

0 commit comments

Comments
 (0)