Skip to content

Commit

Permalink
leadership: avoid potential data race (tikv#6636)
Browse files Browse the repository at this point in the history
close tikv#6635

Signed-off-by: lhy1024 <[email protected]>
  • Loading branch information
lhy1024 authored Jun 20, 2023
1 parent 0934e64 commit 3bdfef1
Showing 1 changed file with 8 additions and 2 deletions.
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()
}

0 comments on commit 3bdfef1

Please sign in to comment.