Skip to content

Commit

Permalink
fix race in parallel tests stretchr/testify#1165
Browse files Browse the repository at this point in the history
  • Loading branch information
SaveTheRbtz committed Apr 11, 2022
1 parent 7158c70 commit 1b20c8a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
7 changes: 6 additions & 1 deletion module/lifecycle/lifecycle.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,17 +49,22 @@ func (lm *LifecycleManager) OnStart(startupFns ...func()) {
// starting up, we will wait for startup to complete before shutting down. After the first
// call, subsequent calls to OnStop do nothing.
func (lm *LifecycleManager) OnStop(shutdownFns ...func()) {
var waitForStartup bool

lm.stateTransition.Lock()
if lm.shutdownCommenced {
lm.stateTransition.Unlock()
return
}
lm.shutdownCommenced = true
if lm.startupCommenced {
waitForStartup = true
}
lm.stateTransition.Unlock()

close(lm.shutdownSignal)
go func() {
if lm.startupCommenced {
if waitForStartup {
<-lm.started
for _, fn := range shutdownFns {
fn()
Expand Down
6 changes: 4 additions & 2 deletions module/lifecycle/lifecycle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,10 @@ func (suite *LifecycleManagerSuite) SetupTest() {
func (suite *LifecycleManagerSuite) TestConcurrentStart() {
var numStarts uint32

lm := suite.lm
for i := 0; i < 10; i++ {
go func() {
suite.lm.OnStart(func() {
lm.OnStart(func() {
atomic.AddUint32(&numStarts, 1)
})
}()
Expand All @@ -46,9 +47,10 @@ func (suite *LifecycleManagerSuite) TestConcurrentStop() {

var numStops uint32

lm := suite.lm
for i := 0; i < 10; i++ {
go func() {
suite.lm.OnStop(func() {
lm.OnStop(func() {
atomic.AddUint32(&numStops, 1)
})
}()
Expand Down

0 comments on commit 1b20c8a

Please sign in to comment.