Skip to content

Commit

Permalink
make sure unlock safe even if listeners panic (zeromicro#383)
Browse files Browse the repository at this point in the history
* make sure unlock safe even if listeners panic

* fix zeromicro#378

* fix zeromicro#378
  • Loading branch information
kevwan authored Jan 13, 2021
1 parent 1f1dcd1 commit 37c3b9f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 18 deletions.
43 changes: 25 additions & 18 deletions core/discov/internal/statewatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ type (
disconnected bool
currentState connectivity.State
listeners []func()
lock sync.Mutex
// lock only guards listeners, because only listens can be accessed by other goroutines.
lock sync.Mutex
}
)

Expand All @@ -32,27 +33,33 @@ func (sw *stateWatcher) addListener(l func()) {
sw.lock.Unlock()
}

func (sw *stateWatcher) notifyListeners() {
sw.lock.Lock()
defer sw.lock.Unlock()

for _, l := range sw.listeners {
l()
}
}

func (sw *stateWatcher) updateState(conn etcdConn) {
sw.currentState = conn.GetState()
switch sw.currentState {
case connectivity.TransientFailure, connectivity.Shutdown:
sw.disconnected = true
case connectivity.Ready:
if sw.disconnected {
sw.disconnected = false
sw.notifyListeners()
}
}
}

func (sw *stateWatcher) watch(conn etcdConn) {
sw.currentState = conn.GetState()
for {
if conn.WaitForStateChange(context.Background(), sw.currentState) {
newState := conn.GetState()
sw.lock.Lock()
sw.currentState = newState

switch newState {
case connectivity.TransientFailure, connectivity.Shutdown:
sw.disconnected = true
case connectivity.Ready:
if sw.disconnected {
sw.disconnected = false
for _, l := range sw.listeners {
l()
}
}
}

sw.lock.Unlock()
sw.updateState(conn)
}
}
}
2 changes: 2 additions & 0 deletions core/proc/shutdown+polyfill.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ package proc

import "time"

// AddShutdownListener returns fn itself on windows, lets callers call fn on their own.
func AddShutdownListener(fn func()) func() {
return fn
}

// AddWrapUpListener returns fn itself on windows, lets callers call fn on their own.
func AddWrapUpListener(fn func()) func() {
return fn
}
Expand Down

0 comments on commit 37c3b9f

Please sign in to comment.