From 0c5963626c45b2971fce766781adcbaf7e9e83ae Mon Sep 17 00:00:00 2001 From: kenwschen Date: Mon, 7 Jun 2021 23:35:31 +0800 Subject: [PATCH] fix(event_bus): panic if multiple goroutine call publish and then wait because of wg's counter can't be a negative number, if call Wait() and then call Add(1) before Wait() complete, it will throw panic "WaitGroup is reused before previous Wait has returned". so add a mutex to prevent this issue. for more detail, see: https://stackoverflow.com/questions/48351816/waitgroup-is-reused-before-previous-wait-unknown-reason --- event_bus.go | 2 ++ event_bus_test.go | 15 +++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/event_bus.go b/event_bus.go index dedc7fd..bec4eb9 100644 --- a/event_bus.go +++ b/event_bus.go @@ -211,5 +211,7 @@ func (bus *EventBus) setUpPublish(callback *eventHandler, args ...interface{}) [ // WaitAsync waits for all async callbacks to complete func (bus *EventBus) WaitAsync() { + bus.lock.Lock() + defer bus.lock.Unlock() bus.wg.Wait() } diff --git a/event_bus_test.go b/event_bus_test.go index 0cdb579..55f4050 100644 --- a/event_bus_test.go +++ b/event_bus_test.go @@ -188,3 +188,18 @@ func TestSubscribeAsync(t *testing.T) { // t.Fail() //} } + +func TestSubscribeAsyncWithMultipleGoroutine(t *testing.T) { + for i := 0; i < 100; i++ { + bus := New() + bus.SubscribeAsync("topic", func() { + time.Sleep(time.Millisecond) + }, false) + bus.Publish("topic") + go func() { + time.Sleep(time.Millisecond) + bus.Publish("topic") + }() + bus.WaitAsync() + } +}